如何使用Jest模拟对象中的特定函数?

umuewwlo  于 2023-11-15  发布在  Jest
关注(0)|答案(3)|浏览(138)

我正在使用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
什么是正确的方法来覆盖对象的方法,而不是设置PostStore中的posts数组通过做一个aerogram调用,它只是设置它与测试数据?

a0x5cqrl

a0x5cqrl1#

我找到了一个jest mock示例函数
例如:

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);
  });
});

字符串

w8biq8rn

w8biq8rn2#

快到了,你要做的就是

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.

字符串

368yc8dk

368yc8dk3#

您可以获取全局fetch并用mock覆盖它,然后在执行的测试中由代码获取。

const globalFetch = global.fetch;
const mockFetch = jest.fn() as jest.MockedFunction<typeof fetch>;

global.fetch = mockFetch;

afterAll(() => {
  global.fetch = globalFetch;
});

字符串

相关问题