【问题标题】:jasmine testing on external library外部库的茉莉花测试
【发布时间】:2013-07-11 04:00:15
【问题描述】:

我正在尝试使用 jasmine 进行一些基本测试。我使用一个外部库,我打算做的是监视/模拟库对象 (d3) 上的方法调用,并确保在 d3 上调用适当的方法。

        var d3Spy = jasmine.createSpyObj('d3', ['select']);
        spyOn(window, 'd3').andReturn(d3Spy);
        expect(d3Spy.select).toHaveBeenCalled();

当在对象上调用“选择”时,我收到此错误。

TypeError: Object function () {
spyObj.wasCalled = true;
spyObj.callCount++;
var args = jasmine.util.argsToArray(arguments);
spyObj.mostRecentCall.object = this;
spyObj.mostRecentCall.args = args;
spyObj.argsForCall.push(args);
spyObj.calls.push({object: this, args: args});
return spyObj.plan.apply(this, arguments);
 } has no method 'select'

我做错了什么?

【问题讨论】:

    标签: testing d3.js jasmine


    【解决方案1】:

    您的代码中的失败如下

    spyOn(window, 'd3').andReturn(d3Spy);
    

    仅当您调用 d3() 时,此行才会返回间谍。因此,它将d3 对象替换为一个函数,该函数在被调用时返回{select: jasmine.createSpy()}。但是使用 d3 你永远不会调用d3() 因为selectd3 的静态成员

    所以解决方案就是监视`d3.select'

    spyOn(d3, 'select')
    

    顺便说一句。像D3 这样使用重链的库的问题在于,它很难模拟。因此,您示例中的 select 间谍必须返回适合 d3 Selections 对象的对象,依此类推。因此,有时不模拟所有内容会更容易。

    【讨论】:

    • 您刚刚指出了我遇到的“所有问题”。由于链式方法调用,事情变得更加复杂,我已经从您提出的解决方案中恢复过来。目前,我已经停止监视所有方法调用,只监视重要且具有简单链式方法调用的方法调用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-27
    • 1970-01-01
    相关资源
    最近更新 更多