如何使用 sinon 在另一个函数(我正在测试)中模拟一个函数? [英] How to mock a function inside another function (which I am testing) using sinon?

查看:31
本文介绍了如何使用 sinon 在另一个函数(我正在测试)中模拟一个函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个函数

Func a() {
    //Do Something
    let c = b();
    return c;
}

我想测试函数 a 和模拟 b() 并在模拟中分配 c.Sinon.Stub(Test,"b").returns("DummyValue");c 应该被分配 DummyValue.

I want to test the function a and mock b() and in the mock want to assign c. Sinon.Stub(Test,"b").returns("DummyValue"); c should be assigned DummyValue.

我该怎么做?

describe("a", () => {
    let a = a();
    //mock b();
    action = execute(a);
    expect(action).should.return.("DummyValue");
})

推荐答案

当我们在同一个文件中有 2 个函数并且想要存根其中一个并测试另一个时.例如,:测试:tests.js

When we have 2 functions in the same file and want to stub one of them and test the other. For example,: Test: tests.js

let ComputeSumStub = sinon.stub(OfflineLoader, "ComputeSum");
const ans = function ()
{
    return 10;
};
ComputeSumStub.returns(ans);
const actualValue: number = OfflineLoader.sum();
expect(actualValue).to.be.equal(10);

开发:foo.js

function sum(): number
{
    return ComputeSum(8, 9);
}

function ComputeSum(a: number, b: number): number
{
    return a + b;
}

我们不能这样做,因为在编译后,函数以不同的签名导出,具有全名,并且在存根时我们存根全局函数,但在从另一个函数中调用它时,我们调用本地函数,因此它没有不工作.有一种解决方法可以做到这一点.

We cannot do that, because after compilation the functions are exported with different signatures, with full name and while stubbing we stub the global function but while calling it from within the other function, we call the local function, hence it doesn’t work. There is a workaround to do that.

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

参考:使用Sinon在同一个文件中存根方法

这篇关于如何使用 sinon 在另一个函数(我正在测试)中模拟一个函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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