Синон, как заглушить метод для модульного тестирования функции Asyn c - PullRequest
0 голосов
/ 08 января 2020

Я пытаюсь написать модульный тест для асинхронной функции c, используя 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)
    })
  })

Ниже приведено определение функции asyn c, которую я тестирую.

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

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

Сбой теста, поскольку возвращаемое обещание отклоняется с сообщением

TypeError: store.query не функция в Object._callee $.

Код, который я тестирую, нигде не вызывает store.query, а также я набрал store.peekRecord, поэтому не уверен, как он вызывается.

1 Ответ

1 голос
/ 08 января 2020

Ваша функция 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

...