[英]Jest not mocking module when using “doMock” to avoid hoisting
I'm trying to mock a class that creates and returns another class. 我正在尝试模拟一个创建并返回另一个类的类。 I've got this: 我有这个:
const mockMethod = jest.fn();
const mockClassA = jest.fn<ClassA>(() => ({
method: mockMethod
}));
jest.mock("../src/ClassB", () => ({
ClassB: {
getClassA: () => new mockClassA()
}
}));
It gets caught out because of the hoisting, the mockClassA
is undefined when jest is mocking `../src/ClassB". 由于提升而被捕获,当jest模拟`../src/ClassB“时, mockClassA
未定义。
I've read if you don't want hoisting, just use doMock
instead: 我已经读过如果你不想要提升,只需使用doMock
:
When using babel-jest, calls to mock will automatically be hoisted to the top of the code block. 使用babel-jest时,对mock的调用将自动提升到代码块的顶部。 Use this method if you want to explicitly avoid this behavior. 如果要明确避免此行为,请使用此方法。
https://jestjs.io/docs/en/next/jest-object#jestdomockmodulename-factory-options https://jestjs.io/docs/en/next/jest-object#jestdomockmodulename-factory-options
When I run with mock
, I get TypeError: mockClassA is not a constructor
, as mockClassA is undefined because the mock
is hoisted above the definition for mockClassA. 当我使用mock
运行时,我得到TypeError: mockClassA is not a constructor
,因为mockClassA是未定义的,因为mock
在mockClassA的定义之上被提升。
When I change mock
to doMock
, it simply does not mock the module - it uses the real thing. 当我将mock
更改为doMock
,它根本不会模拟模块 - 它使用真实的东西。
Edit: Declairing them in-line means I can't easily access the mocked methods for checking: 编辑:在线声明它们意味着我无法轻松访问用于检查的模拟方法:
jest.mock("../src/ClassB", () => ({
ClassB: {
getClassA: () => ({
method: jest.fn()
})
}
}));
Because getClassA
is a function, it's returning a separate instance of the object with method
. 因为getClassA
是一个函数,所以它使用method
返回一个单独的对象实例。
Edit 2: Ah! 编辑2:啊! Managed to inline it like so: 管理内联它就像这样:
jest.mock("../src/ClassB", () => {
const mockMethod: jest.fn();
return {
ClassB: {
getClassA: () => ({
method: mockMethod
})
}
};
});
I think you have 2 options here: 我想你有两个选择:
jest.mock
, inline the mockClassA
and mockMethod
, expose them in the mock and then import from '../src/ClassB' 使用jest.mock
,内联mockClassA
和mockMethod
,在mock中公开它们然后从'../src/ClassB'导入 require
within your test case. 使用doMock,但在测试用例中使用动态require
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.