[英]Testing Promise.then with Jasmine 2
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.我试图监视在 promise.then 中执行的函数,但是我无法获得预期的 call.count() 并且我无法理解我做错了什么。
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:如果您的承诺符合 A+ 规范,那么:
promise.then(function(result) {
this.make();
});
Will not work.不管用。 As the spec requires this
to have no value.由于规范要求this
没有价值。
2.2.5 onFulfilled and onRejected must be called as functions (ie with no this value). 2.2.5 onFulfilled 和 onRejected 必须作为函数调用(即没有这个值)。 [3.2] [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.then(..)
返回的promise.then(..)
的同时fulfill
或reject
其他排队的承诺,除非您这样做:
promise = promise.then(..)
You have to respect the Promise chain by returning a promise in a promise您必须通过在承诺中返回承诺来尊重承诺链
var that = this; // according to MinusFour answer
promise.then(function(result) {
return that.make();
});
return promise;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.