Reputation: 6141
My unit test is not working hitting the then
function for some reason. Here is the test code.
describe("Basic promise test", () => {
it("should trigger .then function", () => {
var mock = jasmine.createSpy('some method');
var promise = new Promise((resolve, reject)=> {
console.log("inside Promise");
resolve('something');
console.log("done!");
});
promise.then(mock);
promise.then(function () { //neither works!
mock();
console.log("resolved"); //code does reach here but only after test fails
});
expect(mock).toHaveBeenCalled();
});
});
I've tried using 'babel-polyfill', 'es6-promise' and 'promise-polyfill' to no avail. What am I doing wrong?
Jsfiddle for this: https://jsfiddle.net/L53zxe39/
Upvotes: 2
Views: 3188
Reputation: 29906
The promise is resolved, but the then
callback is only called in the next microtask, after the check expect(mock).toHaveBeenCalled();
has been made.
It is intended behaviour and designed to prevent ambiguity around promises. A .then
callback is guaranteed to be called later, even if the promise is already resolved.
Asynchronous jasmine tests work in the following way:
describe("Basic promise test", () => {
it("should trigger .then function", (done) => {
var mock = jasmine.createSpy('some method');
var promise = new Promise((resolve, reject)=> {
console.log("inside Promise");
resolve('something');
console.log("done!");
});
promise.then(mock).then(() => {
expect(mock).toHaveBeenCalled();
done();
}).catch(e => {
done.fail(e);
});
});
});
You can use done.fail
to explicitly fail the spec. This is needed to catch and notify jasmine about uncaught exceptions during tests.
Upvotes: 9