我正在尝试测试一个应用程序,但是 jest.spyOn让我发疯。
我正在使用 Node v8.9.4 和 jest v22.2.2
我已经提取了这段代码:
// my-module.js
class MySingletonModule {
constructor() {
this.foo = 'bar';
}
myPromise() {
return new Promise((resolve, reject) => resolve(this.foo));
}
}
module.exports = new MySingletonModule();
<小时/>
// promise.test.js
const singleton = require('./my-module');
describe('Module test-suite', () => {
let spy;
beforeAll(async () => {
spy = jest.fn();
spy = jest.spyOn(singleton, 'myPromise');
});
beforeEach(() => spy.mockReset());
test('Check bar', () => {
return singleton.myPromise().then((bar) => {
expect(bar).toEqual('bar');
});
});
test('Check called times', () => {
singleton.myPromise();
expect(spy).toHaveBeenCalledTimes(1);
});
afterAll(() => {
jest.restoreAllMocks();
});
});
Check bar
测试失败,因为 myPromise
方法未返回 Promise:
如果我评论 spy = jest.spyOn(singleton, 'myPromise');
测试有效..但显然其他测试不起作用..
我希望所有测试都可以与 spyOn
一起使用,因为阅读文档是这样写的:
Note: By default, jest.spyOn also calls the spied method.
我错过了什么吗?
感谢您的帮助
最佳答案
这是没有 Jasmine 的工作片段:
describe('Module test-suite', () => {
let spy;
beforeAll(() => { // get rid of async
spy = jest.fn();
spy = jest.spyOn(singleton, 'myPromise');
});
afterEach(() => spy.mockRestore()); // main difference is here
test('Check bar', () => {
return singleton.myPromise().then((bar) => {
expect(bar).toEqual('bar');
});
});
test('Check called times', () => {
singleton.myPromise();
expect(spy).toHaveBeenCalledTimes(1);
});
afterAll(() => {
jest.restoreAllMocks();
});
});
我认为最好使用 mockRestore
而不是 mockReset
,因为据我从 jest docs 了解到的mockReset
很难清除有关 spy 和 spy 对象的所有信息。 mockRestore
只是清除一些临时数据,例如调用次数。
为什么使用 afterEach
而不是 beforeEach
很重要 - 我不知道:(
我还删除了async
,因为测试失败了。
关于node.js - 返回 Promise 的 jest.spyOn 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49073178/