如何使用 Jest 模拟对象中的特定功能? [英] How to mock specific function in object using Jest?
问题描述
我正在使用 Jest 测试 React/Reflux 应用程序.我在商店中有以下功能:
I'm testing a React/Reflux application using Jest. I have the following function in a store:
onLoad: function() {
console.log("ORIGINAL LOAD");
// http request here
}
我正在尝试模拟它,以便它只做它需要做的事情而不做实际的网络工作:
I'm trying to mock it out so that it just does what it needs to do without doing the actual network stuff:
beforeEach(function() {
// mock out onLoad so instead of making API call the store gets test data
PostStore.onLoad = jest.genMockFunction().mockImplementation(function () {
var p1 = new Post(
"54da7df5119025513400000a", // id
"Test Post", // title
"Kji6ftLjUqhElgnqOBqMUKxYONpU7nK/cu6jTA==
", // owner anonId
"Test Course 1", // course name
"This is a test!", // content
6, // upvotes
2, // downvotes
["Kji6ftLjUqhElgnqOBqMUKxYONpU7nK/cu6jTA==
"] // voter anonIds
);
this.posts = [p1];
console.log("mocked function");
});
// component initialized here
});
然而,似乎模拟函数从未被创建.当我运行测试时,控制台仍然记录 ORIGINAL LOAD
.
However, it seems like the mocked function never even gets created. When I run the tests, the console still logs ORIGINAL LOAD
.
重写对象方法的正确方法是什么,而不是通过执行 ajax 调用在 PostStore
中设置 posts
数组,而是使用测试数据设置它?
What's the correct way to override the object's method so that instead of setting the posts
array in PostStore
by doing an ajax call it just sets it with test data?
推荐答案
我找到了 jest mock 实例函数就在这里
I have found jest mock instance function It's here
例如:
import expect from 'expect';
jest.mock('../libs/utils/Master');
import Master from '../libs/utils/Master';
Master.mockImplementation(() => {
return {
returnOne: jest.fn().mockReturnValueOnce(1)
}
})
describe('test Master', function() {
it('test search', function() {
let master = new Master();
expect(master.returnOne()).toEqual(1);
});
});
这篇关于如何使用 Jest 模拟对象中的特定功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!