繁体   English   中英

未找到 sinon 存根类

[英]sinon stubbed class not found

我开始使用 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 类。

这实际上与存根无关。

您必须将此函数定义为静态方法才能实现此目的:

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

    }
}

然后你可以调用类对象上的方法。

当您编写一个普通的类方法时,您总是必须先实例化该类,然后才能在实例上使用它:

const b = new class_Obj();
b.someFunctionOfClassB();

另请参阅: JavaScript 中的类与静态方法

这是单元测试解决方案:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM