如何使用 Jest 模拟对象中的特定函数? [英] How to mock specific function in object using Jest?

查看:21
本文介绍了如何使用 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆