如何使用jasmine在setTimeout中测试间谍?

时间:2016-06-13 15:10:47

标签: javascript jasmine

我有这样的代码:

it('should call json-rpc', function() {
    var spy = spyOn(object, 'echo');
    if (spy.andCallThrough) {
        spy.andCallThrough();
    } else {
        spy.and.callThrough();
    }
    enter(term, 'echo foo bar');
    setTimeout(function() {
        // here I've got error Expected a spy, but got Function.
        expect(object.echo).toHaveBeenCalledWith('foo', 'bar');
        term.destroy().remove();
    }, 200);
});

我有错误,object.ech不是间谍而是函数,如何检查函数是否在setTimeout中被调用?

编辑:我试过用过这个:

if (jasmine.Clock) {
    jasmine.Clock.useMock();
} else {
    jasmine.clock().install();
}

if (jasmine.Clock) {
    jasmine.Clock.tick(200);
} else {
    jasmine.clock().tick(200);
}
expect(object.echo).toHaveBeenCalledWith('foo', 'bar');

但这也行不通。我有错误

Expected spy echo to have been called with [ 'foo', 'bar' ] but it was never called.  

2 个答案:

答案 0 :(得分:2)

期望应该是针对间谍的本地JavaScript本地变量实例。所以在你的情况下你应该使用:

expect(spy).toHaveBeenCalledWith

答案 1 :(得分:0)

我认为你还必须告诉jasmine在setTimeout之后完成测试。例如。对于jasmine 2.0这样的东西(参见jasmine 1.3及更多链接)

  

你可以使用done,测试回调:

it('should call json-rpc', function(done) {
    var spy = spyOn(object, 'echo');
    if (spy.andCallThrough) {
        spy.andCallThrough();
    } else {
        spy.and.callThrough();
    }
    enter(term, 'echo foo bar');
    setTimeout(function() {
        // here I've got error Expected a spy, but got Function.
        expect(object.echo).toHaveBeenCalledWith('foo', 'bar');
        term.destroy().remove();
        done();
    }, 200);
});

在这里:https://stackoverflow.com/a/10955536/5272567