首页 > 解决方案 > 未找到 sinon 存根类

问题描述

我开始使用 sinon 编写单元测试用例并面临以下问题。

我的文件.js

module.exports = class A{
    constructor(classB_Obj){
        this.classBobj = classB_Obj;
        classBobj.someFunctionOfClassB(); // error coming here
    }
    doSomething(){

    }
}

B类在哪里

myfile2.js

module.exports = class B{
    constructor(arg1, arg2){
        this.arg1 = arg1;
        this.arg2 = arg2;
    }
    someFunctionOfClassB(){

    }
}

当我测试 A 类并使用 sinon 存根 B 类时

const myfile2 = require('../myfile2').prototype;
const loggerStub = sinon.stub(myfile2, 'someFunctionOfClassB');

在执行它时给出异常

classBobj.someFunctionOfClassB 不是函数。

存根的正确方法是什么?我不想实例化 B 类。

标签: javascriptnode.jsunit-testingsinonsinon-chai

解决方案


这是单元测试解决方案:

myfile.js

module.exports = class A {
  constructor(classB_Obj) {
    this.classBobj = classB_Obj;
    this.classBobj.someFunctionOfClassB();
  }
  doSomething() {}
};

myfile2.js

module.exports = class B {
  constructor(arg1, arg2) {
    this.arg1 = arg1;
    this.arg2 = arg2;
  }
  someFunctionOfClassB() {}
};

myfile.test.js

const A = require("./myfile");
const B = require("./myfile2");
const sinon = require("sinon");

describe("52559903", () => {
  afterEach(() => {
    sinon.restore();
  });
  it("should pass", () => {
    const bStub = sinon.createStubInstance(B, {
      someFunctionOfClassB: sinon.stub(),
    });
    new A(bStub);
    sinon.assert.calledOnce(bStub.someFunctionOfClassB);
  });
});

带有覆盖率报告的单元测试结果:

 myfile
    ✓ should pass


  1 passing (10ms)

----------------|----------|----------|----------|----------|-------------------|
File            |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
----------------|----------|----------|----------|----------|-------------------|
All files       |     87.5 |      100 |    57.14 |     87.5 |                   |
 myfile.js      |      100 |      100 |       50 |      100 |                   |
 myfile.test.js |      100 |      100 |      100 |      100 |                   |
 myfile2.js     |    33.33 |      100 |        0 |    33.33 |               3,4 |
----------------|----------|----------|----------|----------|-------------------|

源代码:https ://github.com/mrdulin/mocha-chai-sinon-codelab/tree/master/src/stackoverflow/52559903


推荐阅读