【问题标题】:Sinon: Mock an internal function which is called by named exportSinon:模拟一个由命名导出调用的内部函数
【发布时间】:2020-12-30 22:17:06
【问题描述】:

我必须模拟一个内部调用的函数,但我正在测试的函数是使用 typescript 中的命名导出导出的。

import { internalFunc } from './internal.ts';

const funcToTest = () => {
  internalFunc();   // I need to mock this function
}

export {
  funcToTest
}

现在我的测试文件是这样的,

import { describe } from 'mocha';
import { expect } from 'chai';
import sinon from 'sinon';

import { funcToTest } from './myModule.ts';

describe ('something meaningful', () => {
  it ('should pass', () => {
    sinon.stub();         // I'm stuck here. How do I mock this internalFunc()?
    let result = funcToTest();
  }
}

您能否建议一种模拟internalFunc() 方法的方法?

【问题讨论】:

    标签: javascript typescript unit-testing mocha.js sinon


    【解决方案1】:

    嗯,我自己找到了方法。不确定这是否是解决此问题的正确方法。

    import { describe } from 'mocha';
    import { expect } from 'chai';
    import sinon from 'sinon';
    
    import { funcToTest } from './myModule.ts';
    import * as internal from './internal.ts';
    
    describe ('something meaningful', () => {
      it ('should pass', () => {
        sinon.stub(internal, 'internalFunc').returns('some value');
        let result = funcToTest();
      }
    }
    

    如果有人找到更好的方法来模拟这个internalFunc,那将会很有帮助。

    【讨论】:

      猜你喜欢
      • 2017-07-23
      • 1970-01-01
      • 2021-01-23
      • 2017-10-24
      • 1970-01-01
      • 1970-01-01
      • 2013-08-15
      • 2013-08-11
      • 1970-01-01
      相关资源
      最近更新 更多