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

admin2025-04-19  1

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?

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?

Share Improve this question asked Jun 19, 2012 at 21:03 Greg BaconGreg Bacon 140k34 gold badges194 silver badges250 bronze badges 1
  • What version of Jasmine are you on? – Dancrumb Commented Jul 4, 2012 at 18:37
Add a ment  | 

2 Answers 2

Reset to default 1

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

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).

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1745001602a279259.html

最新回复(0)