类型错误:无法存根不存在的属性

问题描述

我是 nodeJS 的新手,在创建存根时遇到了问题。我有一个类,包含变量和函数。我想为这个场景写 UT。 我正在使用 sinon 为我的类存根函数,这工作正常,但如何处理变量?

const sinon = require("sinon");
const MyClass = require("../MyClass").MyClass;
describe("the functions for fetching the information",function () {
    let requestStub;
    let fileReadStub;
    cont mockVariable = 'abc';
    const mockConfig = {
        "ID" : "abc123xyz","SERVICE_ENABLED" : true
    }
    const mockRequest = {
        "field1": "value1","field2": "value2","field3": "value3"
    }
    beforeEach(function () {
        sandBox = sinon.createSandBox();
        requestStub = sandBox.stub(MyClass,"createRequestForgraphApi").returns(mockRequest);
        sandBox.stub(MyClass,"myVariable").value(mockVariable);
        fileReadStub = sandBox.stub(fs,'readFileSync');
    });
    afterEach(function () {
        sandBox.restore();
    });
    
    it("returns the data if info received from Graph is valid",async function () {
        let actualEvents = [];
        fileReadStub.returns(JSON.stringify(mockConfig));
        actualEvents =  await MyClass.getEvents("token");
        expect(requestStub.calledOnce).to.be.true;
        expect(actualEvents).to.deep.equal(expectedEvents);
    });
});

在我的函数内部,getEvents 依赖 2 个东西,1 个函数“createRequestForgraphApi”和 1 个类变量“myVariable”。由于 createRequestForgraphApi 依赖于更多内部函数,所以我尝试模拟它并且能够做到,但我无法在这里模拟类变量值。

我收到以下变量错误 -

     TypeError: Cannot stub non-existent property myVariable
      at Function.stub (node_modules/sinon/lib/sinon/stub.js:73:15)
      at SandBox.stub (node_modules/sinon/lib/sinon/sandBox.js:331:37)
      at Context.<anonymous> (test/MyClass.spec.js:136:11)

当我为这个类创建对象时,我得到了同样的错误,但对于函数部分。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...