Jasmine间谍重置呼叫不会返回

Jor*_*orn 20 javascript spy jasmine jasmine2.0

我正在使用Jasmine(2.2.0)间谍来查看是否调用了某个回调.

测试代码:

it('tests', function(done) {
  var spy = jasmine.createSpy('mySpy');
  objectUnderTest.someFunction(spy).then(function() {
    expect(spy).toHaveBeenCalled();
    done();
  });
});
Run Code Online (Sandbox Code Playgroud)

这按预期工作.但现在,我正在增加第二个级别:

it('tests deeper', function(done) {
  var spy = jasmine.createSpy('mySpy');
  objectUnderTest.someFunction(spy).then(function() {
    expect(spy).toHaveBeenCalled();
    spy.reset();
    return objectUnderTest.someFunction(spy);
  }).then(function() {
    expect(spy.toHaveBeenCalled());
    expect(spy.callCount).toBe(1);
    done();
  });
});
Run Code Online (Sandbox Code Playgroud)

此测试永远不会返回,因为显然done回调从未被调用过.如果我删除该行spy.reset(),测试确实完成,但显然在最后的期望中失败.然而,这个callCount领域似乎是undefined,而不是2.

Eit*_*eer 34

对于间谍函数,Jasmine 2的语法不同于1.3.在这里查看Jasmine文档.

特别是你重置间谍 spy.calls.reset();

这是测试的样子:

// Source
var objectUnderTest = {
    someFunction: function (cb) {
        var promise = new Promise(function (resolve, reject) {
            if (true) {
                cb();
                resolve();
            } else {
                reject(new Error("something bad happened"));
            }
        });
        return promise;
    }
}

// Test
describe('foo', function () {
    it('tests', function (done) {
        var spy = jasmine.createSpy('mySpy');
        objectUnderTest.someFunction(spy).then(function () {
            expect(spy).toHaveBeenCalled();
            done();
        });
    });
    it('tests deeper', function (done) {
        var spy = jasmine.createSpy('mySpy');
        objectUnderTest.someFunction(spy).then(function () {
            expect(spy).toHaveBeenCalled();
            spy.calls.reset();
            return objectUnderTest.someFunction(spy);
        }).then(function () {
            expect(spy).toHaveBeenCalled();
            expect(spy.calls.count()).toBe(1);
            done();
        });
    });
});
Run Code Online (Sandbox Code Playgroud)

请看这里的小提琴


Ste*_*ush 5

另一种写法:

const spy = spyOn(foo, 'bar');
expect(spy).toHaveBeenCalled();
spy.calls.reset();
Run Code Online (Sandbox Code Playgroud)