开玩笑的嘲笑参考错误 [英] Jest mocking reference error

查看:95
本文介绍了开玩笑的嘲笑参考错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用以下模拟:

I'm trying to use the following mock:

const mockLogger = jest.fn();

jest.mock("./myLoggerFactory", () => (type) => mockLogger);

但是mockLogger会引发参考错误.

but mockLogger throws a reference error.

我知道开玩笑正在试图保护我,使其无法进入模拟范围之外,但是我需要引用jest.fn(),以便断言它已被正确调用.

I know jest is trying to protect me from reaching outside of the scope of the mock, but I need a reference to jest.fn() so I can assert that it was called correctly.

我只是在嘲笑这个,因为我正在对一个库进行一次由内而外的验收测试.否则,我会一直将对记录器的引用作为参数而不是嘲笑贯穿到整个记录器中.

I'm only mocking this because I'm doing an outside-in acceptance test of a library. Otherwise I would thread the reference to the logger all the way through as a parameter rather than mocking.

我该如何实现?

推荐答案

问题是在运行时将jest.mock提升到文件的开头,因此const mockLogger = jest.fn();随后运行.

The problem is that jest.mock are hoisted to at the begin of the file on run time so const mockLogger = jest.fn(); is run afterwards.

要使其正常工作,您必须先进行模拟,然后导入模块并设置间谍程序的实际实现:

To get it work you have to mock first, then import the module and set the real implementation of the spy:

//mock the module with the spy
jest.mock("./myLoggerFactory", jest.fn());
// import the mocked module
import logger from "./myLoggerFactory"

const mockLogger = jest.fn();
//that the real implementation of the mocked module
logger.mockImplementation(() => (type) => mockLogger)

这篇关于开玩笑的嘲笑参考错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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