Javascript 测试承诺。然后是茉莉花2

Javascript 测试承诺。然后是茉莉花2,javascript,jasmine,promise,karma-jasmine,es6-promise,Javascript,Jasmine,Promise,Karma Jasmine,Es6 Promise,我有一个函数正在使用一个承诺,并在该承诺实现时调用另一个函数。我试图监视在promise中执行的函数。然后,我无法获得预期的调用。count(),我无法理解我做错了什么 var MyClass = function() {}; MyClass.prototype.doSomething = function(id) { var promise = this.check(id); promise.then(function(result) { this.make

我有一个函数正在使用一个承诺,并在该承诺实现时调用另一个函数。我试图监视在promise中执行的函数。然后,我无法获得预期的调用。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();
});
这是行不通的。由于规范要求
没有值

2.2.5 OnCompleted和onRejected必须作为函数调用(即不使用此值)。[3.2]

您需要执行以下操作:

var that = this;
promise.then(function(result) {
    that.make();
});
另外,要意识到返回的承诺将尝试在
承诺返回的同时
履行
拒绝
其他排队承诺。然后(…)
,除非您:

promise = promise.then(..)

你必须通过在承诺中返回承诺来尊重承诺链

var=this;//根据四个答案
承诺。然后(功能(结果){
把那个还给我。make();
});
回报承诺;

这是NodeJS代码吗?谢谢!你知道为什么myClass.check.calls.count()等于2而不是1吗?有趣的是,当我将assert语句移到外部时,它会按预期返回1。
doSomething
调用
check
。因此,在调用
然后
处理程序时获得额外计数是有意义的。我不知道为什么以前有人叫它。也许是假的?我不熟悉测试框架。