预期是间谍,但得到了函数

42
我正在尝试为此模块实现一个测试(1)。
我的目的是在触发特定事件时检查是否获取了集合。
正如您从(2)中的注释中所看到的,我收到了消息Error: Expected a spy, but got Function.
该模块可以工作,但测试失败了。有什么想法吗?
// 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
});

代码不够详细,无法看出具体情况。请提供更多内容,不仅包括单个函数,还要包括函数所属的对象定义以及实例化对象的代码。 - Derick Bailey
@DerickBailey 谢谢您的时间。我已经更新了我的问题,并附上了更多的代码。 - Lorraine Bernard
我使用QUnit而不是Jasmine,但你的app.vent.trigger调用应该在"it"方法中而不是beforeEach中,对吗? - codemonkey
@codemonkey,@DerickBailey,实际上我得到了一个不同的错误:期望 spy,但得到了 Function。我更新了我的问题。 - Lorraine Bernard
3个回答

54

你需要进入实际的方法,而在这种情况下,该方法位于原型中。

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 类内部的函数,这样做是否会正常工作? - zero_cool

4

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

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

为什么需要这个原型? - Rebai Ahmed
官方文档中提到了吗? - Rebai Ahmed

0

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接