[英]Jest error: TypeError: Cannot read properties of undefined (reading 'send')
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".所以这个测试应该只通过文本“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') TypeError:无法读取未定义的属性(读取“发送”)
It is because there is no res
object in the getAllUsers
function.这是因为getAllUsers function中没有res
getAllUsers
。 You need to create a mock response
and request
and pass it to the function.您需要创建一个模拟response
和request
并将其传递给 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.注意:您需要查看此URL 才能真正了解我们应该如何使用 Jest 测试快递 API。
In the function, where are you reading users
?在 function 中,您在哪里阅读users
? As the response is dependent on users
so make sure you pass it to the method while testing it.由于响应取决于users
,因此请确保在测试时将其传递给方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.