Grz*_*lik 3 javascript jestjs immutable.js
当尝试使用Jest的.toHaveBeenCalledWith()方法测试传递给函数的参数时,如果我使用ImmutableJS库处理不可变数据结构,则测试失败.测试失败,消息类似于:
Expected mock function to have been called with:
[{"foo": true, "bar": "baz"}]
But it was called with:
[{"foo": true, "bar": "baz"}]
Run Code Online (Sandbox Code Playgroud)
测试看起来类似于:
const expectedArgs = Map({
foo: true,
bar: 'baz'
});
const foo = jest.fn();
bar();
expect(foo).toHaveBeenCalledWith(expectedArgs);
Run Code Online (Sandbox Code Playgroud)
和类似的功能:
const bar = () => {
const baz = Map({});
const bazModified = baz.set('foo', true).set('bar', 'baz');
foo(bazModified);
}
Run Code Online (Sandbox Code Playgroud)
我意识到如果我以这种方式传递参数一切正常:
const bar = () => {
const baz = Map({
foo: true,
bar: 'baz'
});
foo(baz);
}
Run Code Online (Sandbox Code Playgroud)
问题是这是我的函数逻辑的一个很大的简化,我必须使用.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);
Run Code Online (Sandbox Code Playgroud)
另一方面,这确实有效:
expect(result).toEqual(expectedArgs);
Run Code Online (Sandbox Code Playgroud)
因为这表现得非常平等.
你无法用它来测试相等性toHaveBeenCalledWith,因为它baz.set('foo', true)总会返回一个新实例(这是使用不可变数据的重点).
我认为没有办法使toHaveBeenCalledWith行为像toEqual,所以我想要走的路是手动测试模拟调用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);
Run Code Online (Sandbox Code Playgroud)