上一个问题链接
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
最佳答案
与数据库建立连接后需要调用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
回调,因为您要返回一个 promise :
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 => {});
});
当您从测试用例返回 promise 时,测试解决方案将延迟到 promise 解决为止。
关于javascript - NodeJs 在执行测试用例时用 Jest 错误表达 MongoDB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50105649/