【问题标题】:Why doesn’t a Jasmine spy think it was called even though it returned the andReturn value?为什么 Jasmine 间谍即使返回了 andReturn 值也不认为它被调用了?
【发布时间】:2012-07-07 05:27:11
【问题描述】:

我正在尝试调试 jQuery.post 上未触发的间谍,因此作为健全性检查,我尝试了

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

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

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

这失败了

预期 'fooz' 等于 'foo'。

但是当我在andReturn 的参数中将'fooz' 更改为'foo' 时,测试失败了

submitRequest 上的预期间谍已被调用。

间谍正在返回预设值,那么为什么toHaveBeenCalled 会失败?

【问题讨论】:

  • 你用的是什么版本的 Jasmine?

标签: javascript unit-testing jasmine


【解决方案1】:

我知道这不应该是解决方案,但你试过了吗

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

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

expect(submitSpy).toHaveBeenCalled();

因为有时这更有效

【讨论】:

  • 感谢您的建议,但此测试也失败了:“预期已调用 submitRequest 的间谍。”
  • @GregBacon 你试过做一个 console.log(submitSpy) 吗?你得到了什么?这真的很奇怪,你用的是什么框架?Backbone?
【解决方案2】:

您的代码应该可以正常工作。我已经在 jasmine 独立示例上对其进行了测试:

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

我的直觉告诉我,您遇到的问题与 Jasmine 对通话前后的范围界定有关 - 我自己也遇到过类似的令人沮丧的情况。在测试开始时,我会检查以确保环境符合您的预期(例如,间谍被重置)。

【讨论】:

    猜你喜欢
    • 2017-10-20
    • 1970-01-01
    • 2016-02-21
    • 1970-01-01
    • 2019-04-03
    • 2015-01-09
    • 1970-01-01
    • 2022-12-09
    • 2022-01-11
    相关资源
    最近更新 更多