我正在使用 jest 测试用户功能(注册和登录)的 API。
测试代码:
const request = require('supertest');
const app = require('../../app');
describe('Test User Functionality', () => {
test('User should be able to login', async done => {
const response = await request(app)
.post('/api/users/login')
.send({
email: '[email protected]',
password: 'welcome1',
})
.expect(200);
done();
//expect(response.statusCode).toBe(200);
});
test('User should be able to signup', async done => {
const response = await request(app)
.post('/api/users/signup')
.send({
username: 'testuser',
email: '[email protected]',
password: 'welcome1',
})
.expect(200);
done();
//expect(response.statusCode).toBe(200);
});
});
如果我有单个测试,它工作正常,但在描述内进行多个测试,它会显示超时错误。
以下是错误截图:
我尝试添加超时,交换测试,但仍然没有成功。
请大家帮忙!
我在使用异步请求测试我的反应组件时遇到了同样的问题。
发生这种情况是因为您没有正确完成您的请求。
您可以轻松解决这个问题。
选项 1:将
done
移动为 expect
函数调用的第二个参数,如下所示。
const response = await request(app)
.post('/api/users/signup')
.send({
username: 'testuser',
email: '[email protected]',
password: 'welcome1',
})
.expect(200, done);
选项2:使用
end
方法
const response = await request(app)
.post('/api/users/signup')
.send({
username: 'testuser',
email: '[email protected]',
password: 'welcome1',
})
.expect(200)
.end((err, res) => {
// do anything you want!
})
或者你可以查看文档(https://github.com/visionmedia/supertest#readme)!
一个可能的问题可能与快速中间件有关。 要了解您是否属于这种情况,您可以:
app.use(/* middleware */)
docs) 一旦找到超时的原因,您就可以进行更深入的研究。 模拟导致问题的中间件的不同部分:
__mocks__
来模拟第三方库
你的根目录并插入一个文件library_name.js
(这是
手动嘲笑笑话:
文档)app.use(Your.Middleware)
并在中间件文件中/** Possibly imports and some setup here */
// Make sure the function being called is mocked
export default {
Middleware: (req, res, next) => {
next();
},
}
(包含中间件的文件可能包含一些可能导致问题的额外设置。)
我的具体情况: 我在中间件和 Redis 实例化的文件中使用
ioredis
,它多次尝试连接到存储,这导致了超时。