I have a function that is using a promise and calls another function when that promise fulfills. I'm trying to spy the function that executed in promise.then, however I can't get the expected calls.count() and I can't understand what I'm doing wrong.
var MyClass = function() {};
MyClass.prototype.doSomething = function(id) {
var promise = this.check(id);
promise.then(function(result) {
this.make();
});
return promise;
};
MyClass.prototype.make = function() {};
describe('when', function() {
var myClass;
beforeAll(function() {
myClass = new MyClass();
});
it('should', function(done) {
spyOn(myClass, 'check').and.callFake(function() {
return Promise.resolve();
});
spyOn(myClass, 'make');
myClass.doSomething(11)
.then(function() {
expect(myClass.make.calls.count()).toEqual(1); // says it is called 0 times
expect(myClass.check.calls.count()).toEqual(1); // says it is called 2 times
done();
});
});
});
If your promise is compilant with the A+ spec then this:
promise.then(function(result) {
this.make();
});
Will not work. As the spec requires this
to have no value.
2.2.5 onFulfilled and onRejected must be called as functions (i.e. with no this value). [3.2]
You'll need to do:
var that = this;
promise.then(function(result) {
that.make();
});
Also, realize that the returned promise will try to fulfill
or reject
other queued promises at the same time as the promise returned by promise.then(..)
unless you do:
promise = promise.then(..)