[英]Jest es6 class mock returns undefined
I have a simple class that I want to mock and for some reason jest returns undefined.我有一个简单的 class ,我想模拟它,出于某种原因,开玩笑返回未定义。
Here's the code:这是代码:
import { MyClass as myClass } from './my-class';
jest.mock('./my-class', () => jest.fn());
console.log(myClass); // undefined
When I log myClass I get undefined
.当我登录 myClass 我得到
undefined
。
If I mock without mocking the implementation, I get this:如果我在没有 mocking 实现的情况下进行模拟,我会得到:
import { MyClass as myClass } from './my-class';
jest.mock('./my-class');
console.log(myClass);
The code above logs: function MyClass() {return mockConstructor.apply(this,arguments);}
上面的代码记录:
function MyClass() {return mockConstructor.apply(this,arguments);}
Which does not allow for mocking, since it is not a jest.fn()
and it has none of the useful methods like mockImplementation
.这不允许 mocking,因为它不是
jest.fn()
并且它没有像mockImplementation
这样的有用方法。
What is the right way to do it?正确的方法是什么?
You didn't mock the my-class
module correctly.您没有正确模拟
my-class
模块。 You are using Named Exports
, you also need to mock this.您正在使用
Named Exports
,您还需要模拟它。
Eg例如
my-class.ts
: my-class.ts
:
export class MyClass {}
my-class.test.ts
: my-class.test.ts
:
import { MyClass as myClass } from './my-class';
jest.mock('./my-class', () => ({ MyClass: jest.fn() }));
console.log(myClass);
Output: Output:
console.log
{ [Function: mockConstructor]
_isMockFunction: true,
getMockImplementation: [Function],
mock: [Getter/Setter],
mockClear: [Function],
mockReset: [Function],
mockRestore: [Function],
mockReturnValueOnce: [Function],
mockResolvedValueOnce: [Function],
mockRejectedValueOnce: [Function],
mockReturnValue: [Function],
mockResolvedValue: [Function],
mockRejectedValue: [Function],
mockImplementationOnce: [Function],
mockImplementation: [Function],
mockReturnThis: [Function],
mockName: [Function],
getMockName: [Function] }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.