我正在尝试使用以下模拟:
const mockLogger = jest.fn();
jest.mock("./myLoggerFactory", () => (type) => mockLogger);
但是mockLogger会抛出引用错误。
我知道笑话试图保护我免于超出模拟范围,但我需要参考jest.fn()
所以我可以断言它被正确调用。
我只是嘲笑这一点,因为我正在对图书馆进行由外而内的验收测试。否则,我会将对记录器的引用作为参数贯穿始终,而不是进行模拟。
我怎样才能实现这个目标?
问题是jest.mock
在运行时被提升到文件的开头,所以const mockLogger = jest.fn();
之后运行。
为了让它工作,你必须首先模拟,然后导入模块并设置间谍的真正实现:
//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)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)