I am working on an angular(2.4.0)/typescript application that uses a custom currency pipe which internally uses angular's built-in CurrencyPipe for formatting inputted currency strings for both 'en-CA' and 'fr-CA' Canadian locales. While writing unit tests for the french case, for the happy-path case of expecting formatted output for a given valid input string,
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 $');
});
});
I am getting this error,
Expected '7 500 $' to be '7 500 $'.
I did check the instance of of the transformed result and it is a String
. What am I missing? Any help would be appreciated.
Well, the culprit was the grouping/thousand separator used by the angular's built-in CurrencyPipe for 'fr-CA' locale. While checking for the UTF-16 code unit value for each character in the string, I was able to see the grouping/thousand separator character (\u00A0) at index 1 (between 7 and 5 of the pipe's output value '7 500 $') was different from the normal space bar character (\u0020). The space just before the '$' sign in the expected value '7 500 $' was equivalent to \u0020 (normal space bar character) as it was manually appended to the built-in pipe’s formatted result within the custom pipe’s logic.
Hence, as a generic solution to such instances (not really required for my use case) of using locale-dependent pipes (CurrrencyPipe, DecimalPipe), I was able to get the unit test to correctly check for the expected value by making use of the toLocaleString()
method of Number.prototype
property like this,
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 $');
});
});