簡體   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