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

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

我对玩笑测试还很陌生,我想我会为我的一个控件编写一个简单的测试,它只发送一个用户对象数组,或者如果数组为空,则发送一个简单的字符串语句。所以这个测试应该只通过文本“No users found”。

这是我写的简单测试:

test('Should return a string statment *No users found*', () => {
    expect(getAllUsers().toBe('No users found'));
});

不确定我做错了什么...

这是我遇到的错误:

 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')

是因为getAllUsers函数中没有res对象。您需要创建一个模拟 responserequest 并将其传递给函数。

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);
  });
});

注意:您需要检查 this URL 才能真正了解我们应该如何使用 Jest 测试 express API。

在函数中,你在哪里读取users?由于响应取决于 users,因此请确保在测试时将其传递给方法。