我对 Node 和 Express 还很陌生。 并一直尝试使用 mocha、chai 和 chai-http 编写测试代码。 这是部分源代码。
const mongoose = require('mongoose'),
User = require('../../models/user');
const mongoUrl = 'mongodb://xxxxxxxxxxx';
describe('/test', function() {
before('connect', function() {
return mongoose.createConnection(mongoUrl);
});
beforeEach(async function(done) {
try {
await User.remove({}); // <-- This doesn't work
chai.request('http://localhost:3000')
.post('/api/test')
.send(something)
.end((err, res) => {
if (err) return done(err);
done();
});
} catch (error) {
done(error);
}
});
});
我在“npm test”(nyc mocha --timeout 10000 test/**/*.js) 中收到以下错误。
Error: Timeout of 10000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.
我从日志中确认数据库连接工作正常。 似乎我收到了等待 User.remove({}) 的超时错误。 我还尝试了不同的方法,例如 User.save() 但是,我遇到了同样的错误。 我需要对数据库模型和连接做一些特殊的事情吗?
最佳答案
这一切都很简单。
为避免该错误,您不得在 Mocha 中同时使用 done
和 async/await
。使用 async/await
并删除 done
作为函数参数和 done()
调用。或者使用done
。然后删除async/await
。请参阅下面每种情况的示例测试。
将 try/catch
与 async/await
一起使用,就像通常将其与同步代码一起使用一样。
以下是最基本的 Mocha 测试,使用 async/await
和 done
方法测试相同的基本 HTTP 服务器端点。
这是async/await
方法。
it('with async/await', async function() {
const res = await chai.request(server)
.get('/')
.send();
assert.equal(res.status, 200);
});
这是完成
方法。
it('with done & callbacks', (done) => {
chai.request(server)
.get('/')
.end((err, res) => {
assert.equal(res.status, 200);
done();
});
});
对于工作示例,另外旋转 basic Express server作为 src/app.js
中的测试对应项。
参见Chai HTTP插件文档,了解有关请求测试可以做什么的更多信息。
就是这样。
关于node.js - 将await/async 与mocha、chai 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51675305/