最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin3浏览0评论

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

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论