问题描述
我正在测试一个对象是否与一组字段匹配,但其中一个是浮点数,我需要使用。如何在中完成?
I'm testing that an object matches a set of fields, but one of them is floating point and I need to use .toBeCloseTo. How can that be done within one expect?
expect(foo).toMatchObject({
bar: 'baz',
value: ???.toBeCloseTo(5), // TODO
});
我可以使用 expect(foo.value).toBeCloseTo(5)
,但我不想将逻辑分成多个 expect
s,每个浮点数一个。
I could use expect(foo.value).toBeCloseTo(5)
, but I don't want to break the logic into multiple expect
s, one for each floating point number.
推荐答案
问题
表示您可以根据值或针对值匹配属性matchers。
Issue
The docs for toMatchObject
states "You can match properties against values or against matchers".
不幸的是, toBeCloseTo
目前不能用作非对称匹配器,它看起来像。
Unfortunately, toBeCloseTo
is not currently available as an asymmetric matcher, it looks like these are the only asymmetric matchers currently provided by Jest.
如果您正在使用Jest v23或更高版本,您可以创建自己的,基本上复制使用:
If you are using Jest v23 or higher you can create your own, essentially duplicating toBeCloseTo
using expect.extend
:
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
等功能。
Note that expect.extend
creates a matcher that can be used within functions like toMatchObject
only in Jest v23 and higher.
来自由Jest合作者发布:虽然它是暗示但目前没有记录,但Jest断言将非对称匹配器对象评估为中定义。
From this post by a Jest collaborator: "Although it is implied but not currently documented, Jest assertions evaluate asymmetric matcher objects as defined in Jasmine".
使用可以像这样创建:
An asymmetric matcher using the logic from toBeCloseTo
can be created like this:
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
});
});
这篇关于在Jest .toMatchObject中包含toBeCloseTo的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!