Jest的toEqual
匹配器在检查相等性时会考虑空格。在测试中格式化期望值时,不可能以匹配包含换行符,制表符等的字符串的方式执行此操作。
Jest是否提供了一种在匹配时忽略空格的方法?
注意:我编辑了这个问题,使其更具通用性。
答案 0 :(得分:3)
正如@Timo所说,这样做的唯一方法似乎是使用自定义匹配器。以下是基于Jest的toEqual匹配器将所有空格压缩到单个空间以便于阅读的内容。它将处理选项卡,换行符等。它将为您提供非常好的输出,如包含的Jest匹配器:
import { replace, map, equals } from 'ramda';
import { matcherHint, printReceived, printExpected } from 'jest-matcher-utils';
import diff from 'jest-diff';
const replaceWhitespace = replace(/\s+/g, ` `);
const compressWhitespace = map(replaceWhitespace);
const name = `toEqualWithCompressedWhitespace`;
export default (received, expected) => {
const [
receivedWithCompresssedWhitespace,
expectedWithCompresssedWhitespace,
] = compressWhitespace([received, expected]);
const pass = equals(
receivedWithCompresssedWhitespace,
expectedWithCompresssedWhitespace
);
const message = pass
? () =>
`${matcherHint(`.not.${name}`)}\n\n` +
`Uncompressed expected value:\n` +
` ${printExpected(expected)}\n` +
`Expected value with compressed whitespace to not equal:\n` +
` ${printExpected(expectedWithCompresssedWhitespace)}\n` +
`Uncompressed received value:\n` +
` ${printReceived(received)}\n` +
`Received value with compressed whitespace:\n` +
` ${printReceived(receivedWithCompresssedWhitespace)}`
: () => {
const diffString = diff(
expectedWithCompresssedWhitespace,
receivedWithCompresssedWhitespace,
{
expand: this.expand,
}
);
return (
`${matcherHint(`.${name}`)}\n\n` +
`Uncompressed expected value:\n` +
` ${printExpected(expected)}\n` +
`Expected value with compressed whitespace to equal:\n` +
` ${printExpected(expectedWithCompresssedWhitespace)}\n` +
`Uncompressed received value:\n` +
` ${printReceived(received)}\n` +
`Received value with compressed whitespace:\n` +
` ${printReceived(receivedWithCompresssedWhitespace)}${
diffString ? `\n\nDifference:\n\n${diffString}` : ``
}`
);
};
return {
actual: received,
expected,
message,
name,
pass,
};
};
要注册自定义匹配器,您需要使用jest.config.js
字段将包含该文件的文件添加到setupTestFrameworkScriptFile
:
setupTestFrameworkScriptFile: `<rootDir>/path/to/customMatchers.js`,
答案 1 :(得分:2)
据我所知,开箱即用的Jest无法实现这一目标。
然而,write your own reusable matcher using expect.extend
非常简单。从两个字符串中删除所有空格,例如通过str.replace(/\s/g, '')
,比较字符串。
答案 2 :(得分:-1)
虽然这不是直接答案,但您也可以这样做:
mockedFunction.mock.calls[0] // To get array of arguments
// or
mockedFunction.mock.calls[0][0] // to get first argument and so on
然后与相等进行比较。