Mock.mockImplementation() 不起作用 [英] Mock.mockImplementation() not working

查看:41
本文介绍了Mock.mockImplementation() 不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个服务类

Service.js

class Service {
}
export default new Service();

我正在尝试为此提供一个模拟实现.如果我使用这样的东西:

And I am trying to provide a mock implementation for this. If I use something like this:

jest.mock('./Service', () => { ... my mock stuff });

它工作正常,但是我无法访问在模拟之外声明的任何变量,这有点限制,因为我想重新配置模拟返回的内容等.

It works fine, however I'm not able to access any variables declared outside of the mock, which is a bit limiting as I'd like to reconfigure what the mock returns, etc.

我试过了(灵感来自另一篇 StackOverflow 文章:使用 Jest 模拟的服务导致不允许 jest.mock() 的模块工厂引用任何范围外变量"错误)

I tried this (inspired by this other StackOverflow article: Service mocked with Jest causes "The module factory of jest.mock() is not allowed to reference any out-of-scope variables" error)

import service from './Service';

jest.mock('./Service', () => jest.fn);

service.mockImplementation(() => {
    return { ... mock stuff }
);

不幸的是,当我尝试运行它时,出现以下错误:

Unfortunately when I am trying to run this, I get the below error:

TypeError: _Service2.default.mockImplementation is not a function

推荐答案

我和 @Janos 遇到了同样的问题,其他答案也没有帮助.你可以做两件事:

I had same problem as @Janos, the other answers didn't help either. You could do two things :

  1. 如果您只需要模拟来自 Service 的函数,请在您的测试文件中:

import service from './Service';

jest.mock('./Service', () => jest.fn());

service.yourFunction = jest.fn(() => { /*your mock*/ })

如果您需要模拟整个模块:

假设你的 service.js 在 javascript/utils 中,创建一个 javascript/utils/_mocks_ 并在其中创建一个 service.js 文件,然后你可以在这个文件中模拟整个类,例如:

Say your service.js is in javascript/utils, create a javascript/utils/_mocks_ and inside it create a service.js file, you can then mock the entire class in this file, eg:

const myObj = {foo: "bar"}

const myFunction1 = jest.fn(() => { return Promise.resolve(myObj) })

const  myFunction2 = ...

module.exports = {
  myFunction1,
  myFunction2
}

然后在您的测试文件中添加:

then in your test file you just add:

jest.mock('./javascript/utils/service')

...从模拟文件导出的函数将通过您的测试文件执行.

...functions exported from the mockfile will be then hit through your test file execution.

这篇关于Mock.mockImplementation() 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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