【问题标题】:How to mock a function only once in a test suite?如何在测试套件中只模拟一次函数?
【发布时间】:2020-09-07 18:31:07
【问题描述】:

我正在为一个项目编写集成测试。在一个测试套件中,我在多个测试中调用了一个注册端点。大多数时候,我想测试给定某些req 参数的registerUser 函数的实际响应。

这一切都很好,除了我还想测试如果registerUser 函数抛出错误会发生什么。我知道我可以在测试套件之上模拟 registerUser 函数,但这会影响所有测试。我尝试过使用jest.mock 和jest.spyOn,但我还不能让它工作。

如何模拟一次registerUser 函数的响应并在之后恢复它,以免影响套件中的其他测试?

authController.js

router.post('/register', async (req, res) => {
    try {
        const response = await registerUser(req);
        res.status(HttpStatus.OK).json({ response });
    } catch (err) {
        res.status(HttpStatus.INTERNAL_SERVER_ERROR).json({ err });
    }
});

authController.test.js

const faker = require('faker');
const HttpStatus = require('http-status-codes');
const authService = require('../services/authService');

// -- Tests where the response of the registerUser function are not mocked are here -- //

it('Gives a status code 500 when an unexpected error is thrown', async () => {
    const registerUserMock = jest.spyOn(authService, "registerUser");
    registerUserMock.mockReturnValue(() => new Error('Oh snap! Something went wrong.'));

    const res = await agent.post('/register')
        .send({
            email: faker.internet.email(),
            firstname: faker.name.firstName(),
            lastname: faker.name.lastName(),
            password: '123',
            reTypedPassword: '123',
        });

    expect(res.statusCode).toBe(HttpStatus.INTERNAL_SERVER_ERROR);
    
    registerUserMock.mockRestore();
});

// -- more tests -- //

【问题讨论】:

  • 究竟是什么不适用于 jest.spyOn?您省略了与此处相关的 authService。不知道 registerUser 是如何定义和导入的。

标签: node.js mocking jestjs


【解决方案1】:

最简单的方法是

  1. 将应在套件中使用相同模拟响应的测试分组(描述)
  2. 在该套件的 beforeAll 挂钩中模拟响应并保存模拟实例
  3. 在该套件的 afterAll 挂钩中恢复原始实现。
describe('tests with successful auth result', () => {

    let authSpy;

    beforeAll(() => {
        authSpy = jest.spyOn(authService, "registerUser").mockReturnValue(...);
    });

    afterAll(() => {
        authSpy.mockRestore();
    });

    // tests using successful result

});

describe('tests with failing auth result', () => {
    // same but with different spy result
});

注意两件重要的事情:

  • 您需要在从mockReturnValue 返回的模拟实例上调用mockRestore,而不是在初始间谍值上
  • 最好在beforeEach/beforeAll中设置mock并在afterEach/afterAll中恢复它,因为如果你直接在测试中设置和恢复它(it),那么如果测试失败间谍仍然无法恢复,并可能影响以下测试!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-26
    • 2016-05-08
    • 1970-01-01
    • 2021-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多