【发布时间】:2021-08-13 06:05:21
【问题描述】:
我正在尝试使用 jest 测试控制器功能,并且我想测试所有三个状态返回
const messagesSender = async (req, res) => {
try {
const { message } = req.body;
if (!message) {
return res.status(400).send({ message: 'Message cannot be null' });
}
return res.status(200).send(message);
} catch (error) {
return res.status(500).json({ error: 'Internal Error' });
}
};
module.exports = { messagesSender };
测试文件:
const messages = require('../controller/messagesController');
describe('Testing Messages Controller', () => {
it('should return internal error', async () => {
const req = {
body: {
message: 'testing',
},
};
const res = {
send: jest.fn(),
status: jest.fn(() => res),
};
const messageResponse = await messages.messagesSender(req, res);
messageResponse.mockImplementation(() => {
throw new Error('User not found');
});
expect(res.status).toBeCalledWith(500);
});
});
但我收到错误消息:
TypeError: Cannot read property 'mockImplementation' of undefined
我该如何解决这个问题并测试 500 结果?
【问题讨论】: