【问题标题】:Jasmine test fails but 'expected' and 'toBe' strings seem equal?Jasmine 测试失败但 'expected' 和 'toBe' 字符串似乎相等?
【发布时间】:2017-12-28 03:06:51
【问题描述】:

我正在开发一个 angular(2.4.0)/typescript 应用程序,该应用程序使用自定义货币管道,该管道在内部使用 angular 的内置 CurrencyPipe 来格式化两个“en-CA”的输入货币字符串和“fr-CA”加拿大语言环境。在为法语案例编写单元测试时,对于期望给定有效输入字符串的格式化输出的快乐路径案例,

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 $'.

我确实检查了转换结果的 instance of,它是 String。我错过了什么?任何帮助将不胜感激。

【问题讨论】:

    标签: angular typescript jasmine pipe separator


    【解决方案1】:

    好吧,罪魁祸首是 angular 的内置 CurrencyPipe 用于“fr-CA”语言环境的 分组/千分隔符。在检查字符串中每个字符的 UTF-16 代码单元值时,我能够在索引 1 ( 75 之间的管道输出值 '7 500 $')与正常的空格键字符(\u0020)不同。预期值 '7 500 $' 中的 '$' 符号之前的空格等效于 \u0020(普通空格键字符),因为它是手动附加到自定义管道逻辑中内置管道的格式化结果。

    因此,作为使用与语言环境相关的管道(CurrrencyPipe、DecimalPipe)的此类实例(我的用例并非真正需要)的通用解决方案,我能够通过使单元测试正确检查预期值像这样使用Number.prototype属性的toLocaleString()方法,

    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 $');
     });
    });
    

    【讨论】:

    • 那是相当详尽的答案。我想说硬编码测试中的值总是更可取,7 + String.fromCharCode(parseInt('a0', 16)) ...
    • @estus - 好点。对于特定的测试规范,这就足够了。但是,正如我在回答中指出的那样,这个想法是展示一种简单的方法来获取管道中使用的特定于语言环境的分隔符,只需知道语言环境本身,而不必真正挖掘 char 或其相应的 unicode。谢谢。
    • 只是一些背景:utf16 'a0' 是“无分隔空间”(html 编码  ),所以7 500 不会在行尾换成7(newline)500100,00 € 也一样(所以 100,00(newline)€ 不会发生,这看起来很傻......)。顺便说一句,格式化 Date() 时不使用 (因此您可以在一行中设置日期,在另一行设置月份)
    猜你喜欢
    • 1970-01-01
    • 2014-04-20
    • 1970-01-01
    • 1970-01-01
    • 2017-11-03
    • 2019-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多