在Jest和Supertest中重新模拟功能

时间:2020-02-12 17:39:20

标签: typescript unit-testing jestjs supertest ts-jest

总体问题:当我使用Jest重新模拟不同测试的功能时,使用Supertest进行端点测试时不会使用新定义的模拟实现。

我有一个运行Express(v4.7.1)驱动的API的Node.js(v11.15.0)服务器,我正在尝试使用Jest(v ^ 25.1.0)作为模拟框架+ Expect库和Supertest进行测试(v ^ 4.0.2)用于调用API端点。所有文件均以Typescript编写,并生成用于运行测试的Javascript文件。

我从文件example.ts中导出了一组函数:

import { importName } from 'import_module';
...

export function a(param: paramType) {
  ...
}

export function b(param: paramType) {
  ...
}

在我的Express应用程序的主app.ts文件中,我将所有这些功能导入为:import * as exampleUtils from '../example_path'。我将这些功能(exampleUtils.a(...))用作app.ts文件中的中间件。

为了测试某些端点,我想模拟一些测试的功能,并为其他一些测试使用其原始功能。我尝试将功能的模拟实现更改为要测试的测试,但是当我使用Supertest击中API端点时,仅使用初始的模拟实现。

我尝试了几种不同的方法来更改实现并重置Superset API:

endpoint.spec.ts

jest.mock('../example_path', () => ({
    ... (other_functions)
    a: jest.fn(_ => dummy_actions),
}));
import * as exampleUtils from '../example_path';
const mockedExampleUtils = mocked(exampleUtils);
// mocked is a fn from ts-jest, required to get past
// Typescript's typecheckers mock functions

beforeEach(() => {
    jest.clearAllMocks();
});

import app from 'express_app_path'
import supertest from 'supertest'

const request = supertest(app);

describe('test set 1', () => {

    // In these tests, we want the dummy_actions functionality
    // In these cases, it acts correctly

    it('test 1.1', async () => {
        const res = await request.get(`/endpoint`)
            .expect(XXX);
        expect(mockedExampleUtils.a).not.toHaveBeenCalled();
        ...
    });
    ...

});

describe('test set 2', () => {

    // In these tests, we want the original functionality
    // However, it still uses dummy_actions

    beforeEach(async () => {
        mockedExampleUtils.a.mockImplementation(
            jest.requireActual('../example_path').a,
        );
    });

    it('test 2.1', async () => {
        const res = await request.get(`/endpoint`)
            .expect(XXX);
        // mockedExampleUtils.a will still use dummy_actions
        expect(mockedExampleUtils.a).toHaveBeenCalled1Times(1);
        ...
    });
    ...

});

我尝试了resetModules的不同组合,将app的{​​{1}}更改为import,并重新要求使用require,并且改为在单个spyOn中使用doMock,并使用beforeEach进行初始化。

为什么实施不会反映在我的端点测试中?感谢您提供任何见识。

0 个答案:

没有答案