当尝试使用 Jest 的 .toHaveBeenCalledWith()
方法测试传递给函数的参数时,如果我使用 ImmutableJS 库处理不可变数据结构,测试将失败。测试失败并显示类似于此的消息:
Expected mock function to have been called with:
[{"foo": true, "bar": "baz"}]
But it was called with:
[{"foo": true, "bar": "baz"}]
测试看起来与此类似:
const expectedArgs = Map({
foo: true,
bar: 'baz'
});
const foo = jest.fn();
bar();
expect(foo).toHaveBeenCalledWith(expectedArgs);
类似这样的函数:
const bar = () => {
const baz = Map({});
const bazModified = baz.set('foo', true).set('bar', 'baz');
foo(bazModified);
}
我意识到如果我以这种方式传递参数一切正常:
const bar = () => {
const baz = Map({
foo: true,
bar: 'baz'
});
foo(baz);
}
问题是,这是对我函数逻辑的极大简化,我必须使用 .set 来构造对象。有人知道为什么 .set 方法无法正确评估吗?
最佳答案
所以您的测试失败了,因为 toHaveBeenCalledWith
只有在实体的实例完全相同时才会通过。它类似于以下内容,但同样失败:
const expectedArgs = Map({
foo: true,
bar: 'baz'
});
const input = Map({
foo: false,
bar: 'baz'
});
const result = input.set('foo', true);
expect(result).toBe(expectedArgs);
另一方面,这确实有效:
expect(result).toEqual(expectedArgs);
因为这执行了深度相等。
您无法使用 toHaveBeenCalledWith
来测试相等性,因为 baz.set('foo', true)
将始终返回一个新实例(是使用不可变数据的重点)。
我认为没有办法让 toHaveBeenCalledWith
表现得像 toEqual
,所以我想要走的路是用 手动测试模拟调用>等于
:
const expectedArgs = Map({
foo: true,
bar: 'baz'
});
const foo = jest.fn();
bar();
// foo.mock.calls[0][0] returns the first argument of the first call to foo
expect(foo.mock.calls[0][0]).toEqual(expectedArgs);
请参阅 toBe 上的文档, toEqual , 和 mock calls
关于javascript - 使用不可变数据结构时 Jest 模拟函数参数不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41004578/