73 lines
2.3 KiB
Plaintext

== Why is this an issue?
The ``++done++`` callback of Mocha is used to signal the end of an asynchronous test. It is called when the test is complete, either successfully or with an error. It is important not to follow the ``++done++`` callback with code because the test may not have completed yet, and the code may execute before the test is finished. This can lead to unpredictable results and make it difficult to debug issues.
It is recommended to use the ``++done++`` callback only to signal the end of the test and handle any necessary cleanup or assertions before the callback.
Here's a bad example of using Mocha's ``++done++`` callback:
[source,javascript,diff-id=1,diff-type=noncompliant]
----
const expect = require("chai").expect;
describe('My test suite', function() {
it('should do something asynchronously', function(done) {
setTimeout(function() {
expect(2 + 2).to.equal(4);
expect('hello').to.have.lengthOf(5);
done();
console.log('Test has completed.'); // Noncompliant: Code after calling done, which may produce unexpected behavior
}, 1000);
});
});
----
Since the ``++console.log++`` statement is executed after calling ``++done()++``, there is no guarantee that it will run after the test has fully completed. It may be correctly executed, but it might as well be assigned to a different test, no test, or even completely ignored.
To fix this, the `done` callback should be called after the ``++console.log++`` statement.
[source,javascript,diff-id=1,diff-type=compliant]
----
const expect = require("chai").expect;
describe('My test suite', function() {
it('should do something asynchronously', function(done) {
setTimeout(function() {
expect(2 + 2).to.equal(4);
expect('hello').to.have.lengthOf(5);
console.log('Test has completed.');
done();
}, 1000);
});
});
----
== Resources
=== Documentation
* Mocha Documentation - https://mochajs.org/#asynchronous-code[Asynchronous code]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
Move this code before the call to "done".
=== Highlighting
Primary: The first line of code which can be executed after a call to "done()"
Secondary: every call to "done() which can be executed before this code
message: 'Call to "done()".'
endif::env-github,rspecator-view[]