2017-07-21 69 views
0

我正在使用角度(2.4.0)/打字稿應用程序,該應用程序使用自定義貨幣管道,內部使用角度的內置CurrencyPipe格式化輸入的貨幣字符串'en-CA'和'fr-CA'加拿大語言環境。雖然編寫單元測試的法國情況下,期望格式輸出給定的有效輸入字符串的幸福路徑的情況下,茉莉花測試失敗,但'預期'和'toBe'字符串似乎相同?

describe('for French locale',() => { 
// get the mock custom currency pipe instance for 'fr-CA' locale as 'currencyPipeForFR' 
it('should be formatted for fr-CA locale',() => { 
    expect(currencyPipeForFR.transform('7500')).toBe('7 500 $'); 
}); 
}); 

我收到此錯誤,

Expected '7 500 $' to be '7 500 $'. 

我沒有檢查實例的轉換結果,它是String。我錯過了什麼?任何幫助,將不勝感激。

回答

3

好了,罪魁禍首是由所使用的分組/千分角的內置CurrencyPipe爲 'FR-CA' 語言環境。而檢測用於所述字符串中的每個字符的UTF-16碼單位值,我能夠看到分組/千分字符(\ u00A0)在索引(之間和的管道的輸出值'7 500 $')與正常的空格欄字符(\ u0020)不同。 '$'登錄預期值'7 500 $'之前的空間等同於\ u0020(普通空格鍵字符),因爲它被手動附加到自定義管道的內置管道格式化結果中邏輯。因此,作爲使用區域依賴管道(CurrrencyPipe,DecimalPipe)的這種實例(對於我的用例來說並非真正需要)的通用解決方案,我能夠通過單元測試正確檢查期望值利用toLocaleString()方法Number.prototype屬性這樣,

describe('for French locale',() => { 
// get the custom currency pipe instance for 'fr-CA' locale as 'currencyPipeForFR' 
const thousandSeparator =() => { 
    return (1000).toLocaleString('fr-CA').substring(1, 2); 
} 
it('should be formatted for fr-CA locale',() => { 
    expect(currencyPipeForFR.transform('7500')).toBe('7' + thousandSeparator() + '500 $'); 
}); 
}); 
+0

這是相當詳盡的答案。我會說硬編碼測試中的值總是更可取,'7 + String.fromCharCode(parseInt('a0',16))...' – estus

+0

@estus - 好點。對於特定的測試規範,這就足夠了。但是,正如我的回答中指出的那樣,這個想法是顯示一種簡單的方法來獲取管道中使用的特定於語言環境的分隔符,只需知道語言環境本身,而不必實際查找char或其對應的unicode。謝謝。 – amal