- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我正在测试一个对象是否匹配一组字段,但其中一个是 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/
我对我的 Mongoose 模型进行了测试,虽然一个模型的测试运行完全正常,但另一个模型基本上是一个副本 - 不起作用。老实说我不明白这个问题。我尝试删除一些属性或添加硬编码值以真正 100% 完全匹
我对我的 Mongoose 模型进行了测试,虽然一个模型的测试运行完全正常,但另一个模型基本上是一个副本 - 不起作用。老实说我不明白这个问题。我尝试删除一些属性或添加硬编码值以真正 100% 完全匹
我正在使用 Jest 来测试我的 Node 应用程序,以下情况验证了一些数据已添加到数据库中(考虑 DB 逻辑工作正常): it("should add empty string hooks if n
我正在测试一个对象是否匹配一组字段,但其中一个是 float ,我需要使用 .toBeCloseTo .如何在一个 expect 内完成? expect(foo).toMatchObject({
我写了下面的测试: it('Can decrement the current step', function () { expect(reducer(TestState, { type: '
假设某个东西返回一个复杂的对象: const value = { ..., client: { ... }, ... }; 我想测试一堆属性,对于client我想确保它有一定的
我想用 jest 测试返回的对象是否符合我的预期。 我正在尝试这个: const desiredResult = { host: '192.168.1.1', port: expect.any
我正在使用 JEST 匹配器 toMatchObject 来确保对象包含多个属性并且一些值是静态的,而其他一些值应该匹配特定的正则表达式 问题是:当静态值不匹配时,输出也会显示正则表达式值不匹配,尽管
我有一个快速 API 端点,它返回一个对象,并且在该对象上有一个属性(在我们下面的示例中为 property3),它的值是日期。 例如 res.body = { "property1
我正在测试一个 React 应用程序,它基本上遵循了标准的、官方认可的 create-react-app 设置。 我的测试如下: import React from 'react'; import {
我是一名优秀的程序员,十分优秀!