[英]Testing Promise.then with Jasmine 2
我有一個使用承諾的函數,並在該承諾實現時調用另一個函數。 我試圖監視在 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();
});
});
});
如果您的承諾符合 A+ 規范,那么:
promise.then(function(result) {
this.make();
});
不管用。 由於規范要求this
沒有價值。
2.2.5 onFulfilled 和 onRejected 必須作為函數調用(即沒有這個值)。 [3.2]
你需要做:
var that = this;
promise.then(function(result) {
that.make();
});
此外,請注意,返回的承諾將嘗試在promise.then(..)
返回的promise.then(..)
的同時fulfill
或reject
其他排隊的承諾,除非您這樣做:
promise = promise.then(..)
您必須通過在承諾中返回承諾來尊重承諾鏈
var that = this; // according to MinusFour answer
promise.then(function(result) {
return that.make();
});
return promise;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.