问题
docs for toMatchObject 声明“您可以将属性与值或匹配器进行匹配”。
很遗憾,toBeCloseTo 目前不能用作非对称匹配器,它看起来像 these are the only asymmetric matchers currently provided by Jest。
解决方案
如果您使用的是 Jest v23 或更高版本,您可以创建自己的,基本上是使用 expect.extend 复制 toBeCloseTo:
expect.extend({
toBeAround(actual, expected, precision = 2) {
const pass = Math.abs(expected - actual) < Math.pow(10, -precision) / 2;
if (pass) {
return {
message: () => `expected ${actual} not to be around ${expected}`,
pass: true
};
} else {
return {
message: () => `expected ${actual} to be around ${expected}`,
pass: false
}
}
}
});
const foo = {
bar: 'baz',
value: 4.9999
};
test('foo', () => {
expect(foo.value).toBeAround(5, 3); // SUCCESS in Jest > v20
expect(foo).toMatchObject({
bar: 'baz',
value: expect.toBeAround(5, 3) // SUCCESS only in Jest > v23
});
});
请注意,expect.extend 创建的匹配器只能在 Jest v23 及更高版本中用于 toMatchObject 等函数中。
替代解决方案
来自 Jest 合作者的 this post:“虽然它是隐含的但目前没有记录,但 Jest 断言将非对称匹配器对象评估为 defined in Jasmine”。
使用the logic from toBeCloseTo 的非对称匹配器可以这样创建:
const closeTo = (expected, precision = 2) => ({
asymmetricMatch: (actual) => Math.abs(expected - actual) < Math.pow(10, -precision) / 2
});
const foo = {
bar: 'baz',
value: 4.9999
};
test('foo', () => {
expect(foo).toMatchObject({
bar: 'baz',
value: closeTo(5, 3) // SUCCESS
});
});