我对玩笑测试相当陌生,并且认为我应该为我的一个控件编写一个简单的测试,该测试仅发送一组用户对象,或者如果该数组为空则发送一个简单的字符串语句。所以这个测试应该只传递文本“No users found”。
这是我写的简单测试:
test('Should return a string statment *No users found*', () => {
expect(getAllUsers().toBe('No users found'));
});
Run Code Online (Sandbox Code Playgroud)
不知道我在这里做错了什么......
这是我收到的错误:
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 |
Run Code Online (Sandbox Code Playgroud)
Apo*_*ara 12
类型错误:无法读取未定义的属性(读取“发送”)
res这是因为函数中没有对象getAllUsers。您需要创建一个模拟response并将request其传递给函数。
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);
});
});
Run Code Online (Sandbox Code Playgroud)
注意:您需要检查此URL 才能真正了解我们应该如何使用 Jest 测试 Express API。
在函数中,你在哪里阅读users?由于响应取决于,users因此请确保在测试时将其传递给方法。
| 归档时间: |
|
| 查看次数: |
87471 次 |
| 最近记录: |