【发布时间】: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 是如何定义和导入的。