【问题标题】:Jasmine - How to Spy on a Function with no ImplementationJasmine - 如何在没有实现的情况下监视函数
【发布时间】:2019-01-09 02:57:12
【问题描述】:

我有我想要测试的脚本 (playground.efs)。但是,它使用 eSignal API,所以我必须监视其中的任何功能。

我在设置 spyOn 时遇到问题,我不知道应该反对什么。通过测试testEfsCode(),需要为getCurrentBarIndex() 创建一个间谍。由于getCurrentBarIndex() 不属于任何对象,我该如何存根呢?

我当前的代码遇到的错误是:

Error: <spyOn> : getCurrentBarIndex() method does not exist
Usage: spyOn(<object>, <methodName>)

TestSpec.js

var util = require('../../../Interactive Data/Formulas/My Formulas/playground.efs');

describe("Utils", function() {
      it("should return true", function() {
            var spy = spyOn(util.testEfsCode, 'getCurrentBarIndex').and.callThrough();
            expect(util.testEfsCode()).toBe(true);
      });
});

playground.efs(测试脚本)

function testEfsCode(){
    getCurrentBarIndex();
    return true;
}

// Check For EFS
if ( typeof module !== 'undefined' && module.hasOwnProperty('exports') )
{
    module.exports = {
        testEfsCode: testEfsCode
    }
}

getCurrentBarIndex() 是 eSignal 提供的一个函数,所以我没有它的代码。该函数仅在脚本加载到 eSignal 时运行。

【问题讨论】:

  • 您有getCurrentBarIndex 的任何文档吗?它在哪里?它是一个全局函数吗?您是否尝试过使用 spyOn(window, "getCurrentBarIndex") 进行间谍活动?
  • getCurrentBarIndex() 是 eSignal 提供的函数。只有在 eSignal 应用程序中运行脚本时才能调用它。另外,我没有在我的代码中使用window,所以我得到 ReferenceError: window is not defined

标签: javascript unit-testing jasmine


【解决方案1】:

我能够从这个问题Using Jasmine to spy on a function without an object找到解决方案

我所要做的就是使用createSpy

getCurrentBarIndex = jasmine.createSpy().and.returnValue(8);
expect(util.testEfsCode()).toBe(8);

【讨论】:

  • 哇哦!我到处找这个。谢谢大佬
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-09-14
  • 2012-03-19
  • 1970-01-01
  • 2010-09-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多