Reputation: 47
I'm trying to test a controller function using jest, and i want to test all three status return
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 };
Test file:
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);
});
});
But i'm receiving the error:
TypeError: Cannot read property 'mockImplementation' of undefined
How can i fix this and test the 500 result?
Upvotes: 0
Views: 386
Reputation: 3294
it('should return internal error', async () => {
const req = {
body: {
message: 'testing',
},
};
const res = {
send: jest.fn().mockImplementation(() => {
throw new Error('User not found');
}),
status: jest.fn(() => res),
};
await messages.messagesSender(req, res);
expect(res.status.mock.calls[1][0]).toBe(500);
});
In your case send
function returning nothing and causing this problem. In this case status
method have been called twice, so you need to check the second call.
Upvotes: 1