Angular数字管道测试:空格不匹配问题求助(Jest+测试库)
优雅断言本地化格式数值的正确性
测试失败的核心原因是法语本地化数字格式使用的是非断空格( ),而你手动编写的预期值用了普通空格,导致字符串匹配失败。以下是几种专注于验证数值本身的解决方案:
方法1:提取文本转换为数字断言
直接提取DOM文本,移除所有非数字字符后转为数字,只验证数值是否正确,完全忽略格式差异:
it('should be equal to 234567', () => { const formattedText = screen.getByTestId('number-format').textContent; const numericValue = parseInt(formattedText.replace(/\D/g, ''), 10); expect(numericValue).toBe(234567); });
方法2:利用Angular DecimalPipe生成预期值
注入Angular的DecimalPipe,用它生成和组件中完全一致的本地化格式字符串,避免手动编写格式错误:
import { DecimalPipe } from '@angular/common'; it('should display the correctly formatted number', async () => { const { inject } = await render(MyComponentToTestComponent); const decimalPipe = inject(DecimalPipe); const expectedText = decimalPipe.transform(234567, '1.0-0', 'fr-FR'); expect(screen.getByTestId('number-format').textContent).toBe(expectedText); });
方法3:标准化空格后断言
如果仍想比较字符串,可以移除所有空白字符(包括非断空格)后直接匹配纯数字字符串:
it('should match the numeric value ignoring formatting', () => { const elementText = screen.getByTestId('number-format').textContent; const normalizedText = elementText.replace(/\s/g, ''); expect(normalizedText).toBe('234567'); });
推荐使用方法1,它最贴合你“不在意格式,只想验证数值本身”的需求,完全规避本地化格式带来的字符串匹配问题。
内容的提问来源于stack exchange,提问作者leducBigood
相关产品推荐
相关产品推荐

