Javascript 如何使用jasmine在setTimeout中测试spy?

Javascript 如何使用jasmine在setTimeout中测试spy?,javascript,jasmine,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(functi

我有这样的代码:

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.echo不是间谍而是函数,我如何检查函数是否在setTimeout中被调用

编辑:我已尝试使用此选项:

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

但这也不起作用。我有错误

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

期望值应该在spy的本地JavaScript局部变量实例上。因此,在您的情况下,您应该使用:

expect(spy).toHaveBeenCalledWith

我想你还得告诉jasmine测试是在
设置超时后完成的。例如,对于jasmine 2.0类似的内容(参见jasmine 1.3及更多内容的链接)

您可以使用“完成”测试回调:

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

此处显示:

我认为期望值应该是spy的局部变量,您将其称为spy,因此:
expect(spy)。toHaveBeenCalledWith
。你试过了吗?@hightempo是的,它可以工作,你可以把这个作为一个答案。
一起调用。你不应该给matcher打电话吗?@alecxe-是的,我只是发布了部分代码,@jcubic需要更改才能工作。整行应该是
expect(spy).toHaveBeenCalledWith('foo','bar')一对夫妇的建议,考虑使用$TimeOutt并调用它作为OSESSET到StudiTimeOut.此外,您还可以添加afterEach()函数来执行以下操作:term.destroy().remove();
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);
});