上一个问题链接
Open Question
方案
我试图测试我的GET端点路由是否正常工作我已经设置正确并且我已经通过运行服务器进行了测试。但我的测试用例给了我以下错误
Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.
我已经搜索了一下,并尝试了所有可能的解决方案,但它仍然给我同样的错误。
代码
const request = require ('supertest');
const app = require ('../../app');
const db = require ('../../db.js');
const url = process.env.MONGO_URI || 'mongodb://localhost:27017'
beforeAll (done => {
db.connect (url, err => {
if (err) {
console.log ('Unable to connect', err);
process.exit (1);
}else{
console.log('Succesfully connected')
}
});
});
afterAll (done => {
db.close ();
});
test ('should response the GET method',done => {
const res = request (app).get ('/expense');
return res
.then (json => {
console.log ("Length",json.body.length);
expect (json.body.length).toBe (1, done ());
})
.catch (err => {});
},10000);
测试输出
● Console
console.log test/express/startupTest.test.js:12
Succesfully connected
console.log test/express/startupTest.test.js:26
Length 1
● should response the GET method
Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.
at pTimeout (node_modules/jest-jasmine2/build/queueRunner.js:53:21)
at Timeout.callback [as _onTimeout] (node_modules/jsdom/lib/jsdom/browser/Window.js:523:19)
at ontimeout (timers.js:469:11)
at tryOnTimeout (timers.js:304:5)
at Timer.listOnTimeout (timers.js:264:5)
Test Suites: 1 failed, 2 passed, 3 total
Tests: 1 failed, 6 passed, 7 total
Snapshots: 1 passed, 1 total
Time: 6.58s
答案 0 :(得分:1)
在与DB建立连接后,您需要调用done
回调。
beforeAll (done => {
db.connect (url, err => {
if (err) {
console.log ('Unable to connect', err);
process.exit (1);
}else{
console.log('Succesfully connected');
done();
}
});
});
与afterAll
相同:
afterAll (done => {
db.close (() => done());
});
此外,您不需要在测试用例中使用done
回调,因为您要返回一个承诺:
test ('should response the GET method', () => {
const res = request (app).get ('/expense');
return res
.then (json => {
console.log ("Length",json.body.length);
expect (json.body.length).toBe (1);
})
.catch (err => {});
});
当您从测试用例返回承诺时,测试解决方案将被延迟,直到承诺结算。