Reputation: 5042
Promise just won't resolve in unit test.
it('should break', function(done){
const promise = Promise.resolve([1, 2, 3, 4 , 5]);
promise.then(function(){
expect(true).to.be.false;
done();
});
});
I have also tried this. (This is actually works in my seperate new sample project i created but this is not working in my real project so this is weird
import { expect } from 'chai';
describe('Hello function', function () {
it('should return hello world', function () {
const promise = Promise.resolve(1);
return promise.then(function () {
expect(true).to.be.false;
});
});
});
Background "karma-mocha": "^1.3.0", "karma-webpack": "^2.0.1", "karma-chai": "^0.1.0", "karma-chrome-launcher": "^2.2.0", "typescript": "~2.3.4", "tslint-loader": "^3.3.0",
In karma.config.js
frameworks: ['mocha', 'chai'], browsers: ['ChromeHeadless'],
Error message i got
✖ should break
HeadlessChrome 0.0.0 (Mac OS X 10.12.6)
Error: Timeout of 9999ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.
Upvotes: 0
Views: 5789
Reputation: 99591
There's 2 ways to do asynchronous tests with mocha. Using done()
or by returning a promise.
Because you're using promises, just returning the promise makes the most sense. This example removes done
and returns the promise.
it('should break', function(){
const promise = Promise.resolve([1, 2, 3, 4 , 5]);
return promise.then(function(){
expect(true).to.be.false();
});
});
Rewritten as async/await + arrow functions:
it('should break', async () => {
await [1, 2, 3, 4 , 5];
expect(true).to.be.false();
});
Using done()
is possible but you shouldn't mix returning promises and calling done()
.
Upvotes: 1
Reputation: 2330
you have to return the promise and call done() after your assertion.
it('should break', function(done){
const promise = Promise.resolve([1, 2, 3, 4 , 5]);
return promise.then(function(){
expect(true).to.be.false;
done();
});
});
Upvotes: -1