简体   繁体   English

开玩笑-如何在函数中模拟方法

[英]Jest - how to mock a method within a function

I have an ES6 class A, that I need to test, the only thing I want to change is the implementation of one method, and all the other things to remain as they are. 我有一个ES6类A,需要测试,我唯一想更改的就是一种方法的实现,而其他所有东西则保持不变。

First, I wanted manually to create a mock class like "myMock extends A" where I would change that method and use it for tests, but there were some problems. 首先,我想手动创建一个类似“ myMock extended A”的模拟类,在该类中我将更改该方法并将其用于测试,但是存在一些问题。

Anyway, is there another way with jest to specify replacement of a specific method within a class? 无论如何,还有什么用笑话来指定类中特定方法的替换吗?

What I tried to do now is following: 我现在尝试做的是:

jest.mock("../myclass", () => {
return jest.fn().mockImplementation(() => {
    return {
        loadPopularItems: jest.fn(() => new Promise((resolve): void => 
           resolve()))
    };
  });
 });

This now gives me an error that myclass is not a constructor: 现在这给了我myclass不是构造函数的错误:

TypeError: myclass`.default is not a constructor TypeError:myclass`.default不是构造函数

All I want to do is remove some async method from there, that makes HTTP requests. 我要做的就是从那里删除一些异步方法,该方法发出HTTP请求。

You can stub out the method on the prototype in your test: 您可以在测试中将方法存入原型:

A.prototype.loadPopularItems = jest.fn()

Or you can use jest.spyOn to allow for easily resetting mocks: 或者,您可以使用jest.spyOn来轻松重置jest.spyOn

jest.spyOn(A.prototype, "loadPopularItems");
jest.restoreAllMocks(); // avoids having to manually track mocks

Better yet, have your class accept whatever object/function makes HTTP requests as a constructor argument: 更好的是,让您的类接受构成HTTP请求的任何对象/函数作为构造函数参数:

class A {
  constructor(http) {
    this.http = http;
  }

  loadPopularItems() {
     return this.http.fetchSomething();
  }
}

Then in your tests you can just pass a fake implementation: 然后在测试中,您可以通过一个伪造的实现:

const fakeHttp = {
  fetchSomething: jest.fn()
};

const instance = new A(fakeHttp);

This is generally the preferable over stubbing out methods. 通常,这比结束方法更可取。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM