在开玩笑中为 es6 类的静态方法创建模拟实现



我正在测试一个函数,该函数在内部从(es6类(控制器调用一个静态方法,该方法返回API获取的结果。由于我正在编写一个单元测试,并且控制器有自己的测试,所以我想模拟(技术上是假的(类中的静态方法,以给我不同类型的响应。

// Controller.js
class Controller {
static async fetchResults() {} // the method I want to fake
}
// func.js - the function I am writing the test for
const func = async (ctx) => {
const data = await Controller.fetchResults(ctx.req.url)
if (containsErrors(data)) ... // do some logic
return { ...data, ...otherStuff }
}

这种伪造static async fetchResults()的尝试没有任何作用,测试尝试调用原始控制器的fetchResults方法。

// func.test.js
describe('when data is successfuly fetched', () => {
jest.mock('./Controller.js', () => jest.fn().mockImplementation(() => ({
fetchResults: jest.fn(() => mockResponse),
});
it('returns correct information', async () => {
expect(await func(context)).toEqual({ ...mockResponse, ...otherStuff });
});
});

下一次尝试看起来mock在某种程度上起作用,但返回的值是undefined而不是{ ...mockResponse, ...otherStuff },这表明整个类都在被模拟,但由于fetchResultsstatic方法而不是实例方法,所以找不到它。

import Controller from './Controller.js'
describe('when data is successfuly fetched', () => {
Controller.mockImplementation(jest.fn(() => ({
fetchHotel: () => { ...mockResponse, ...otherStuff }
})
it('returns correct information', async () => {
expect(await func(context)).toEqual({ ...mockResponse, ...otherStuff });
});
});

您可以使用jest.spyOn(object,methodName(来执行此操作。

例如

controller.js:

export class Controller {
static async fetchResults(url) {
return { result: 'real result' };
}
}

func.js:

import { Controller } from './controller';
const func = async (ctx) => {
const data = await Controller.fetchResults(ctx.req.url);
// do some logic
return { ...data };
};
export { func };

func.test.js:

import { Controller } from './controller';
import { func } from './func';
describe('60776211', () => {
it('should pass', async () => {
const fetchResultsSpy = jest.spyOn(Controller, 'fetchResults').mockResolvedValueOnce({ result: 'fake data' });
const ctx = { req: { url: 'example.com' } };
const actual = await func(ctx);
expect(actual).toEqual({ result: 'fake data' });
fetchResultsSpy.mockRestore();
});
});

带覆盖率报告的单元测试结果:

PASS  stackoverflow/60776211/func.test.ts
60776211
✓ should pass (5ms)
---------------|---------|----------|---------|---------|-------------------
File           | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
---------------|---------|----------|---------|---------|-------------------
All files      |   91.67 |      100 |      75 |   88.89 |                   
controller.ts |      80 |      100 |      50 |      75 | 3                 
func.ts       |     100 |      100 |     100 |     100 |                   
---------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        4.922s, estimated 11s

最新更新