Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest error: TypeError: Cannot read properties of undefined (reading 'send')

Tags:

node.js

jestjs

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 |
like image 209
cnak Avatar asked Nov 22 '25 22:11

cnak


1 Answers

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.

like image 76
Apoorva Chikara Avatar answered Nov 25 '25 15:11

Apoorva Chikara