I'm fairly new to jest testing and thought I'd write a simple test for one of my controls that simply sends an array of user objects, or a simple string statement if the array is empty. So this test should just pass the text "No users found".
Here is the simple test I wrote:
test('Should return a string statment *No users found*', () => {
expect(getAllUsers().toBe('No users found'));
});
Not sure what I'm doing wrong here...
Here is the error I'm getting:
TypeError: Cannot read properties of undefined (reading 'send')
6 |
7 | export const getAllUsers = (req, res) => {
> 8 | if(users.length === 0) res.send('No users found');
| ^
9 | res.send(users);
10 | };
11 |
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.