小编典典

使用Sinon在同一文件中存根方法

reactjs

我试图对文件中的一个函数进行单元测试,同时在SAME文件中存根另一个函数,但是未应用模拟程序,而是调用了real方法。这是一个例子:

// file: 'foo.js'

export function a() {
   // .....
}

export function b() { 
   let stuff = a(); // call a
   // ...do stuff
}

而我的测试:

import * as actions from 'foo';

const aStub = sinon.stub(actions, 'a').returns('mocked return');
actions.b(); // b() is executed, which calls a() instead of the expected aStub()

阅读 230

收藏
2020-07-22

共1个答案

小编典典

一些重组可以使这项工作。

我使用了commonJS语法。在ES6中也应以相同的方式工作。

foo.js

const factory = {
  a,
  b,
}
function a() {
  return 2;
}

function b() {
  return factory.a();
}

module.exports = factory;

test.js

const ser = require('./foo');
const sinon = require('sinon');

const aStub = sinon.stub(ser, 'a').returns('mocked return');
console.log(ser.b());
console.log(aStub.callCount);

输出量

模拟回报

1个

2020-07-22