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

问题描述

我有一个服务班

Service.js

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文章的启发:)

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

推荐答案

该模拟等于jest.fn.您需要调用jest.fn来创建模拟函数.

The mock is equal to jest.fn. You need to call jest.fn to create a mocked function.

所以这个:

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

应该是:

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

这篇关于Mock.mockImplementation()无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-31 21:14