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

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

问题描述

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

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);

输出


模拟返回

mocked return

1

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

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