我正在使用 Jest 测试 React/Reflux 应用程序。我在商店中有以下功能:
onLoad: function() {
console.log("ORIGINAL LOAD");
// http request here
}
我试图模拟它,以便它只做它需要做的事情,而不需要做实际的网络事情:
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==\n", // owner anonId
"Test Course 1", // course name
"This is a test!", // content
6, // upvotes
2, // downvotes
["Kji6ftLjUqhElgnqOBqMUKxYONpU7nK/cu6jTA==\n"] // voter anonIds
);
this.posts = [p1];
console.log("mocked function");
});
// component initialized here
});
但是,模拟函数似乎从未被创建。当我运行测试时,控制台仍然记录ORIGINAL LOAD。
重写对象方法的正确方法是什么,以便不通过执行 ajax 调用来设置 PostStore 中的 posts 数组,而是使用测试数据来设置它?
请您参考如下方法:
我找到了 jest 模拟实例函数 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);
});
});






