问题:
I keep getting a timeout error, it keeps telling me to enusre I have called done(), even though I have.
const mocha = require('mocha');
const assert = require('asser...
可以将文章内容翻译成中文,广告屏蔽插件会导致该功能失效:
问题:
I keep getting a timeout error, it keeps telling me to enusre I have called done(), even though I have.
const mocha = require('mocha');
const assert = require('assert');
const Student = require('../models/student.js');
describe('CRUD Tests',function(){
it('Create Record',function(done){
var s = new Student({
name: "Yash"
});
s.save().then(function(){
assert(s.isNew === false);
done();
});
});
});
Result is -
CRUD Tests 1) Create Record
0 passing (2s) 1 failing
1) CRUD Tests Create Record: Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves. (/home/yash/Documents/Development/Node/MongoCRUD/test/CRUD_test.js)
回答1:
Note that as written, your unit test ignores the fact that save()
might reject instead of resolving. Whenever you use this done
construct, make sure your unit test handles an error scenario, like this:
s.save().then(function() {
assert(s.isNew === false);
done();
}).catch(error => {
done(error);
});
Alternatively, since Mocha has built-in support for promises, you can remove the done
parameter and return the promise directly, like this:
it('Create Record', function() {
// ...
return s.save().then(function() {
assert(s.isNew === false);
});
});
The advantage with this approach is a reject promise will automatically fail the test, and you don't need any done()
calls.
回答2:
I guess that your mocha runs without being connected to your database. So .save()
is waiting for a connection which it never get and your mocha timeout.
You can initialize your software system before to run any Mocha test.
For example, connect a database.
// ROOT HOOK Executed before the test run
before(async () => {
// connect to the database here
});
// ROOT HOOK Excuted after every tests finished
after(async () => {
// Disconnect from the database here
});