用Jasmine 2测试Promise.then

时间:2015-10-01 18:28:27

标签: javascript jasmine promise karma-jasmine es6-promise

我有一个使用promise的函数,并在该promise实现时调用另一个函数。我试图窥探在promise中执行的函数。然后,我无法获得预期的calls.count(),而我无法理解我做错了什么。< / p>

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();
            });
    });
});

2 个答案:

答案 0 :(得分:2)

如果您的承诺与A +规格保持一致,那么:

promise.then(function(result) {
    this.make();
});

不行。由于规范要求this没有价值。

  

2.2.5 onFulfilled和onRejected必须作为函数调用(即没有此值)。 [3.2]

Promises A+ 2.2.5

你需要这样做:

var that = this;
promise.then(function(result) {
    that.make();
});

此外,请注意,返回的承诺将在fulfill返回的承诺的同时尝试rejectpromise.then(..)其他排队的承诺,除非您这样做:

promise = promise.then(..)

答案 1 :(得分:0)

你必须通过在承诺中回复承诺

来尊重Promise链
var that = this; // according to MinusFour answer
promise.then(function(result) {
   return that.make();
});

return promise;
相关问题