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

查看:135
本文介绍了如何使用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==\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.

However, it seems like the mocked function never even gets created. When I run the tests, the console still logs ORIGINAL LOAD.

重写对象方法的正确方法是什么,而不是通过执行ajax调用来设置PostStore数组,而仅通过测试数据来设置它,而不是在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?

推荐答案

几乎在这里,您要做的就是

Almost there, all you need to do is

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.

这篇关于如何使用Jest模拟对象中的特定功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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