gpt4 book ai didi

javascript - 在 Jest .toMatchObject 中包含 toBeCloseTo

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:57:08 28 4
gpt4 key购买 nike

我正在测试一个对象是否匹配一组字段,但其中一个是 float ,我需要使用 .toBeCloseTo .如何在一个 expect 内完成?

expect(foo).toMatchObject({
bar: 'baz',
value: ???.toBeCloseTo(5), // TODO
});

我可以使用 expect(foo.value).toBeCloseTo(5),但我不想将逻辑分解为多个 expect,每个一个 float 。

最佳答案

问题

docs for toMatchObject声明“您可以将属性与值或匹配器进行匹配”。

不幸的是,toBeCloseTo 目前不能用作非对称匹配器,它看起来像 these are the only asymmetric matchers currently provided by Jest .


解决方案

如果您使用 Jest v23 或更高版本,您可以创建自己的,本质上是复制 toBeCloseTo使用 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 等函数中使用。


替代方案

来自 this post由 Jest 合作者撰写:“虽然暗示但当前未记录,但 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
});
});

关于javascript - 在 Jest .toMatchObject 中包含 toBeCloseTo,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53369407/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com