如何解决如何在测试套件中仅模拟一次功能?
我正在为一个项目编写集成测试。在一个测试套件中,我正在多个测试中调用注册端点。大多数时候,我想测试在给定registerUser
参数的情况下req
函数的实际响应是什么。
一切正常,除了我还想测试如果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 -- //
解决方法
最简单的方法是
- 将应该使用相同模拟响应的测试分组(在描述中)
- 在该套件的
beforeAll
挂钩中模拟响应并保存模拟实例 - 将原始实现恢复到该套件的
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
});
请注意两件重要的事情:
- 您需要调用
mockRestore
返回的 mock实例上的mockReturnValue
,而不是初始间谍值 - 最好在
beforeEach
/beforeAll
中设置模拟并在afterEach
/afterAll
中将其还原,因为如果您直接在测试中进行设置和还原({ {1}}),那么如果测试失败,间谍将无法恢复,并可能影响以下测试!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。