javascript 开玩笑地将一个对象传递给 expect().toBeCalledWith()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47953305/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Jest passing an object to expect().toBeCalledWith()
提问by Nader Hisham
I'm using jest to test my react components and I'm using expect(...).toBeCalledWith(...);to test if a function has been called with specific parameters, and it works fine with value types.
我正在使用 jest 来测试我的 React 组件,并且我正在使用它expect(...).toBeCalledWith(...);来测试是否使用特定参数调用了一个函数,并且它适用于值类型。
The problem is I want to test a function that takes object as a parameter so when you call expect(myFunc).toBeCalledWith(object);the test always fails because of course the two object compared to each other do not have the same reference.
问题是我想测试一个将对象作为参数的函数,所以当你调用expect(myFunc).toBeCalledWith(object);测试时总是失败,因为这两个对象当然没有相同的引用。
so how can I solve this problem ?
那么我该如何解决这个问题呢?
a sample code of what I'm trying to test is
我要测试的示例代码是
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);
});
An error message would be something like this
错误消息将是这样的
Expected mock function to have been called with:
[{"bar": "bar", "foo": "foo"}]
But it was called with:
[{"bar": "bar", "foo": "foo"}]
Update
更新
it seems the below code works fine
似乎下面的代码工作正常
expect(api.submitForm).toBeCalledWith(
expect.objectContaining({
foo : 'foo',
bar: 'bar'
}),
);
however, if the object contains a property with array value, the above solution doesn't work
但是,如果对象包含具有数组值的属性,则上述解决方案不起作用
const obj = {
foo : ['foo1', 'foo2'],
bar: 'bar'
}
回答by Kevin Amiranoff
Looking at the jest doc (https://facebook.github.io/jest/docs/en/expect.html#expectobjectcontainingobject). It seems you can do something like this:
查看笑话文档(https://facebook.github.io/jest/docs/en/expect.html#expectobject containsobject)。看来你可以做这样的事情:
expect(api.submitForm).toBeCalledWith(
expect.objectContaining({
foo : 'foo',
bar: 'bar'
}),
);

