我正在使用jest来测试我的反应组件,我正在使用expect(…).toBeCalledWith(…);测试是否已使用特定参数调用函数,并且它与值类型一起正常工作.
问题是我想测试一个将对象作为参数的函数,所以当你调用expect(myFunc).toBeCalledWith(object);测试总是失败,因为当然两个对象相互比较没有相同的参考.
那我怎么解决这个问题呢?
我要测试的示例代码是
it('the function should be called with the correct object', () => {
api.submitForm = jest.fn().mockReturnValue(Promise.resolve());
const wrapper = shallow(<component />);
const instance = wrapper.instance();
instance.submitForm();
const object = {
foo : 'foo',
bar: 'bar'
};
// this always fails even the function is called with the same object values
expect(api.submitForm).toBeCalledWith(object);
});
错误消息将是这样的
Expected mock function to have been called with:
[{"bar": "bar", "foo": "foo"}]
But it was called with:
[{"bar": "bar", "foo": "foo"}]
更新
看来下面的代码工作正常
expect(api.submitForm).toBeCalledWith(
expect.objectContaining({
foo : 'foo',
bar: 'bar'
}),
);
但是,如果对象包含具有数组值的属性,则上述解决方案不起作用
const obj = {
foo : ['foo1', 'foo2'],
bar: 'bar'
}
解决方法:
看着开玩笑的文档(https://facebook.github.io/jest/docs/en/expect.html#expectobjectcontainingobject).看来你可以这样做:
expect(api.submitForm).toBeCalledWith(
expect.objectContaining({
foo : 'foo',
bar: 'bar'
}),
);