【问题标题】:Expected a spy, but got Function期待一个间谍,但得到了功能
【发布时间】:2016-09-23 08:31:44
【问题描述】:

我正在尝试为此模块 (2) 实施测试 (1)。
我的目的是检查触发特定事件时是否提取了集合。
从我在 (2) 中的评论中可以看出,我收到了消息 Error: Expected a spy, but got Function.
该模块工作,但测试失败。有任何想法吗?


(1)

// jasmine test module

describe('When onGivePoints is fired', function () {
    beforeEach(function () {
        spyOn(this.view.collection, 'restartPolling').andCallThrough();
        app.vent.trigger('onGivePoints');
    });
    it('the board collection should be fetched', function () {
        expect(this.view.collection.restartPolling).toHaveBeenCalled();
       // Error: Expected a spy, but got Function.
    });
});

(2)

// model view module
return Marionette.CompositeView.extend({
    initialize: function () {
        this.collection = new UserBoardCollection();
        this.collection.startPolling();
        app.vent.on('onGivePoints', this.collection.restartPolling);
    },
    // other code
});

【问题讨论】:

  • 没有足够的代码来查看发生了什么。请不仅仅包括单个函数 - 至少包括函数所属的对象定义,以及实例化对象的代码。
  • @DerickBailey 感谢您抽出宝贵时间。我用模式代码更新了我的问题。
  • 我使用 QUnit 而不是 Jasmine,但您对 app.vent.trigger 的调用不应该在“it”方法中而不是 beforeEach 中吗?
  • @codemonkey,@DerickBailey,实际上我得到了一个不同的错误:Expected a spy, but got Function。我更新了我的问题。

标签: javascript backbone.js jasmine marionette


【解决方案1】:

你需要进入实际的方法,在这种情况下是在原型上。

describe('When onGivePoints is fired', function () {
    beforeEach(function () {
        spyOn(UsersBoardCollection.prototype, 'restartPolling').andCallThrough();
        app.vent.trigger('onGivePoints');
    });
    it('the board collection should be fetched', function () {
        expect(UsersBoardCollection.prototype.restartPolling).toHaveBeenCalled();
    });
});

监视原型是一个不错的技巧,当您无法到达要监视的实际实例时,可以使用它。

【讨论】:

  • 如果该函数在原型上不存在,并且是 React 类中的一个函数,这是否可以工作?
【解决方案2】:

我也遇到了同样的问题,但我通过在函数调用中传递一个参数来解决它。然后你必须像这样在it中编写你的测试用例

var data = {name:"test"}
spyOn(UsersBoardCollection.prototype, "restartPolling").and.callThrough();
UsersBoardCollection.prototype.restartPolling(data);
expect(UsersBoardCollection.prototype.restartPolling).toHaveBeenCalled();

【讨论】:

    【解决方案3】:

    我有这个错误是因为我加载了两个版本的 sinon,或者我没有正确初始化 sinon-jasmine。当我在我的规范设置中显式加载 sinon 和 sinon jasmine 时,它​​开始正常运行。

    【讨论】:

      猜你喜欢
      • 2020-11-09
      • 1970-01-01
      • 2016-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多