如何使用Jest模拟对象中的特定功能?

Hug*_*ugo 6 tdd mocking reactjs jestjs refluxjs

我正在使用Jest测试React/Reflux应用程序.我在商店里有以下功能:

onLoad: function() {
  console.log("ORIGINAL LOAD");
  // http request here
}
Run Code Online (Sandbox Code Playgroud)

我试图嘲笑它,以便它只是做它需要做的事情而不做实际的网络东西:

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
});
Run Code Online (Sandbox Code Playgroud)

但是,看起来似乎从未创建过模拟函数.当我运行测试时,控制台仍然会记录ORIGINAL LOAD.

覆盖对象方法的正确方法是什么,而不是通过执行ajax调用来设置posts数组,PostStore它只是用测试数据设置它?

Yi *_*ang 6

我发现 jest 模拟实例函数 就在这里

例如:

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);
  });
});
Run Code Online (Sandbox Code Playgroud)


mds*_*ubi 5

几乎就在那里,你需要做的就是

const onLoad = jest.fn().mockImplementation(function () {
    var p1 = new Post();//Add your stuff here
    this.posts = [p1];
    console.log("mocked function");
  });
PostStore.onLoad = onLoad.bind(PostStore); //PostStore is your object.
Run Code Online (Sandbox Code Playgroud)