我想了解Sinon是否可用于从另一个内部调用的类中添加一个函数。

例如,有一个dbutil类:

class DBUtils {
    getMyResult(var1, var2){
        return new Promise((resolve) => {
            console.log("calling real getMyResult");//I still see this in the log
            resolve(var1 + var2);
        });
    }
}
module.exports = DBUtils;


在另一个类dummyService中调用它:

const dbUtils = new DBUtils();
class dummyService {
    getResult(var1, var2){
    //initially in my code, it returns a promise,
    //but I have replaced it with your code
    return dbUtils.getMyResult(var1, var2).then(item =>{
        console.log("finish getting my result!");
        console.log("here is my result: " + item);
        return item;
    });
}
module.exports = dummyService;


这是我的单元测试文件:(@Mark_M建议应用代码更改)

describe("dummy Test", function () {
var service = new DummyService();

const stub = sinon.stub(DBUtils.prototype, 'getMyResult');
stub.resolves("1234");

it("get result", function() {
    service.getResult("ab", "cd").then(item => {
        console.log(item);
    });
});
});


谁能帮助我了解为什么我的存根不起作用?以及如何在dbUtil类中存根getMyResult函数?

===============解决方案===================

我错过了两件事:


我应该存根DBUtils.prototype



sinon.stub(DBUtils.prototype, 'getMyResult').resolves("1234");




在测试中导入DBUtils时出现错字。


在dummyService中,我有

const DBUtils = require(./dbutils);


但是,在测试文件中,我有

const DBUtils = require(./DBUtils);


不知何故,sinon并没有抱怨它,这就是为什么我的存根在原始方法中从未被注入的原因....在测试中更正了导入之后,我现在可以看到存根的结果被注入了。

最佳答案

由于getMyResult()DBUtils类的类方法,因此需要对DBUtils的原型进行存根。像这样:

DBUtils.getMyResult()返回一个承诺。因此,您无需在dummyService.getResult()中的诺言中重新包装它。如果您只返回原始的诺言,就可以更轻松地进行推理(和测试):

dummyService:

const DBUtils = require('./DBUtils')

class dummyService {
    getResult(var1, var2){
        const dbUtils = new DBUtils() // <- I assume you are making an instance somewhere
        return dbUtils.getMyResult(var1, var2).then(item =>{
            console.log("finish getting my result!");
            console.log("here is my result: " + item);
            return item // <- if you want to access item in then you need to return it
        });
    }
}
module.exports = dummyService;


现在在test.js中:

const DBUtils = require('./DBUtils')
const DummyService = require('./dummy')
const sinon = require('sinon')

// stub the prototype
const stub = sinon.stub(DBUtils.prototype, 'getMyResult')
stub.resolves("Stubbed: 1234")

// make an instance of the service
const service = new DummyService()
service.getResult("ab", "cd").then(item => {
    console.log(item)
    // this prints 'stubbed: 1234'
    // item is "abcd", which is the returned value of the real getMyResult method.
    // the expectation is, item should be "1234" as specified in the stub.
});

10-06 11:00