簡體   English   中英

使用 sinon 在類的實例上存根方法

[英]Stubbing a method on instance of a class with sinon

我是用 sinon 測試的新手,並試圖掌握存根的竅門。 我正在嘗試測試一個函數,該函數接收一個請求對象,從中獲取一些屬性,並將其傳遞給一個向外部服務發出 get 請求的類的實例。

前任:

exports.getMyThings = (req) => {
  const reqOpts = {
    qs: req.query
  };

  return apiInstance.get(req.route, reqOpts);
};

apiInstance在我導出getMyThings函數的文件中實例化。

我正在嘗試刪除apiInstance.get方法,以便我可以測試我的getMyThings函數是否正常工作並向它傳遞正確的參數。

我試圖通過將類導入到我的測試文件中來編寫存根,然后創建一個存根實例:

const MyClass = require('.../blahblah)
const apiInstance = sinon.createStubInstance(MyClass);

const apiInstance = new MyClass();
apiInstance.get = sinon.stub();

但是在我的getMyThings函數中, apiInstance.get方法不是包裝的方法 - 它是原始方法。 包裝的實例僅存在於我的測試中。 這是有道理的,但我不知道如何解決它。 任何想法表示贊賞。

您可以使用,

const returnMe = () => 'sinon rocks!';
sinon.stub(apiInstance, 'get').callsFake(returnMe);


result = apiInstance.get();
// Do asssertion for result to equal to the returnMe();

希望能幫助到你。

這是單元測試解決方案:

index.js

const MyClass = require("./api");
const apiInstance = new MyClass();

exports.getMyThings = (req) => {
  const reqOpts = {
    qs: req.query,
  };

  return apiInstance.get(req.route, reqOpts);
};

api.js :

function MyClass() {}
MyClass.prototype.get = async function get(route, reqOpts) {
  return "real data";
};

module.exports = MyClass;

index.test.js

const { getMyThings } = require("./");
const sinon = require("sinon");
const { expect } = require("chai");
const MyClass = require("./api");

describe("50726074", () => {
  afterEach(() => {
    sinon.restore();
  });
  it("should pass", async () => {
    const getStub = sinon.stub(MyClass.prototype, "get").resolves("fake data");
    const mReq = { route: "/api/thing", query: { id: "1" } };
    const actual = await getMyThings(mReq);
    expect(actual).to.be.equal("fake data");
    sinon.assert.calledWith(getStub, "/api/thing", { qs: { id: "1" } });
  });
});

帶有覆蓋率報告的單元測試結果:

  50726074
    ✓ should pass


  1 passing (37ms)

---------------|----------|----------|----------|----------|-------------------|
File           |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
---------------|----------|----------|----------|----------|-------------------|
All files      |    95.24 |      100 |    83.33 |    95.24 |                   |
 api.js        |    66.67 |      100 |       50 |    66.67 |                 3 |
 index.js      |      100 |      100 |      100 |      100 |                   |
 index.test.js |      100 |      100 |      100 |      100 |                   |
---------------|----------|----------|----------|----------|-------------------|

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM