Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn’t a Jasmine spy think it was called even though it returned the andReturn value?

I’m trying to debug a spy on jQuery.post that isn’t firing, so as a sanity check, I tried

spyOn(this.viewModel.requests, 'submitRequest').andReturn('fooz');

var ret = this.viewModel.requests.submitRequest();
expect(ret).toEqual('foo');

expect(this.viewModel.requests.submitRequest).toHaveBeenCalled();

This fails with

Expected 'fooz' to equal 'foo'.

But when I change 'fooz' to 'foo' in the argument to andReturn, the test fails with

Expected spy on submitRequest to have been called.

The spy is returning the canned value, so why does toHaveBeenCalled fail?

like image 915
Greg Bacon Avatar asked Jun 19 '12 21:06

Greg Bacon


2 Answers

I know this shouldn't be the solution, but have you tried

var submitSpy = spyOn(this.viewModel.requests, 'submitRequest').andReturn('foo');

var ret = this.viewModel.requests.submitRequest();
expect(ret).toEqual('foo');

expect(submitSpy).toHaveBeenCalled();

Because sometimes this works more consistently

like image 159
Nicola Peluchetti Avatar answered Oct 23 '22 16:10

Nicola Peluchetti


Your code should be working. I have tested it on the jasmine standalone examples:

it("tells the current song if the user has made it a favorite", function() {
  spyOn(song, 'persistFavoriteStatus').andReturn('foo');
  var ret = song.persistFavoriteStatus();
  expect(ret).toEqual('foo');

  expect(song.persistFavoriteStatus).toHaveBeenCalled();
});

My gut tells me that the issue you're experiencing has to do with Jasmine's scoping of before/after calls - I've run into frustrating cases like that myself. In the beginning of the test, I would check to make sure the environment is as you expected (ie, the spies are reset for example).

like image 31
badunk Avatar answered Oct 23 '22 16:10

badunk