我用jest来测试我的react组件,我用expect(...).toBeCalledWith(...);
来测试一个函数是否用特定的参数调用过,它在值类型上运行良好.
问题是,我想测试一个以object为参数的函数,所以当你调用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'
}