簡體   English   中英

Sinon 如何存根方法以對異步函數進行單元測試

[英]Sinon how to stub method for unit testing a Async function

我正在嘗試使用 mocha 和 sinon.js 為異步函數編寫單元測試

下面是我的測試用例

  describe('getOperations', function () {
    let customObj, store, someObj
    beforeEach(function () {
      someObj = {
        id: '-2462813529277062688'
      }
      store = {
        peekRecord: sandbox.stub().returns(someObj)
      }
    })
    it('should be contain obj and its ID', function () {
      const obj = getOperations(customObj, store)
      expect(obj).to.eql(someObj)
    })
  })

下面是我正在測試的異步函數的定義。

async function getOperations (customObj, store) {
  const obj = foo(topLevelcustomObj, store)
  return obj
}

function foo (topLevelcustomObj, store) {
    return store.peekRecord('obj', 12345)
}

測試用例失敗,因為返回的承諾被一條消息拒絕

類型錯誤:store.query 不是 Object._callee$ 的函數。

我正在測試的代碼沒有在任何地方調用store.query並且我也存根了store.peekRecord所以不確定它是如何被調用的。

您的getOperations函數使用async語法,因此您需要在測試用例中使用async/await 而且,它工作正常。

例如index.ts

export async function getOperations(customObj, store) {
  const obj = foo(customObj, store);
  return obj;
}

export function foo(customObj, store) {
  return store.peekRecord("obj", 12345);
}

index.test.ts

import { getOperations } from "./";
import sinon from "sinon";
import { expect } from "chai";

describe("59639661", () => {
  describe("#getOperations", () => {
    let customObj, store, someObj;
    beforeEach(function() {
      someObj = {
        id: "-2462813529277062688",
      };
      store = {
        peekRecord: sinon.stub().returns(someObj),
      };
    });
    it("should pass", async () => {
      const obj = await getOperations(customObj, store);
      expect(obj).to.deep.eq(someObj);
    });
  });
});

100% 覆蓋率的單元測試結果:

  59639661
    #getOperations
      ✓ should pass


  1 passing (14ms)

---------------|----------|----------|----------|----------|-------------------|
File           |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
---------------|----------|----------|----------|----------|-------------------|
All files      |      100 |      100 |      100 |      100 |                   |
 index.test.ts |      100 |      100 |      100 |      100 |                   |
 index.ts      |      100 |      100 |      100 |      100 |                   |
---------------|----------|----------|----------|----------|-------------------|

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

暫無
暫無

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

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