Jest error: TypeError: Cannot read properties of undefined (reading 'send')
TypeError: Cannot read properties of undefined (reading 'send')
It is because there is no res
object in the getAllUsers
function. You need to create a mock response
and request
and pass it to the function.
const sinon = require('sinon');
const mockRequest = () => {
return {
users: [];
};
};
const mockResponse = () => {
const res = {};
res.status = sinon.stub().returns(res);
res.json = sinon.stub().returns(res);
return res;
};
describe('checkAuth', () => {
test('should 401 if session data is not set', async () => {
const req = mockRequest();
const res = mockResponse();
await getAllUsers(req, res);
expect(res.status).toHaveBeenCalledWith(404);
});
});
Note: You need to check this URL to actually understand how we should test the express API with Jest.
In the function, where are you reading users
? As the response is dependent on users
so make sure you pass it to the method while testing it.