2

I have code like this:

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

and I've got error that object.echo is not a spy but function, how can I check if function was called in setTimeout?

EDIT: I've tried use this:

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

and

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

but this also don't work. I've got error

Expected spy echo to have been called with [ 'foo', 'bar' ] but it was never called.  
jcubic
  • 61,973
  • 54
  • 229
  • 402
  • I think the expectation should just be on your local variable for the spy, which you are calling spy so: `expect(spy).toHaveBeenCalledWith`. Have you tried that? – hightempo Jun 13 '16 at 18:15
  • @hightempo yes it work, you can add this as an answer. – jcubic Jun 14 '16 at 14:48

2 Answers2

2

Expectations should be on the local JavaScript local variable instance for the spy. So in your case you should use:

expect(spy).toHaveBeenCalledWith
hightempo
  • 469
  • 2
  • 8
  • `toHaveBeenCalledWith`..should not you be calling the matcher? – alecxe Jun 14 '16 at 16:50
  • 1
    @alecxe - yes, I was just posting part of the code -- the part that @jcubic would have to change to get it to work. The full line would be `expect(spy).toHaveBeenCalledWith('foo', 'bar');` – hightempo Jun 14 '16 at 16:53
  • A couple suggestions, consider using $timeout and calling flush on it as opossed to setTimeout. Also you can add an afterEach() function to do things like tearing down: term.destroy().remove(); – terpinmd Jun 14 '16 at 17:03
0

I think you have to also tell jasmine the test is done after the setTimeout. E.g. for jasmine 2.0 something like this (see link for jasmine 1.3 and more)

You can use done, the test callback:

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

taken here: https://stackoverflow.com/a/10955536/5272567

Community
  • 1
  • 1
Matthias
  • 3,160
  • 2
  • 24
  • 38