首页 > 解决方案 > Sinon:模拟一个由命名导出调用的内部函数

问题描述

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

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()方法?

标签: javascripttypescriptunit-testingmocha.jssinon

解决方案


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

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,那将会很有帮助。


推荐阅读