使用Sinon在同一文件中的存根方法 [英] Stubbing method in same file using Sinon

查看:31
本文介绍了使用Sinon在同一文件中的存根方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对文件中的函数进行单元测试,同时存根同一文件中的另一个函数,但没有应用模拟,而是调用了真正的方法.举个例子:

I'm trying to unit test a function in a file while stubbing another function in the SAME file, but the mock is not being applied and the real method is being called. Here's an example:

// 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()

推荐答案

一些重组可以实现这一目标.

Some restructuring can make this work.

我使用了 commonJS 语法.在 ES6 中也应该以同样的方式工作.

I've used commonJS syntax. Should work in the same way in ES6 as well.

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

这篇关于使用Sinon在同一文件中的存根方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆