Проблема модульного теста с Мокко и Синоном с использованием JavaScript - PullRequest
0 голосов
/ 22 февраля 2019

Я пытаюсь использовать mocha и sinon для тестирования фрагмента кода, который использует сервис AWS.Ниже кода:

exports.init = ({ athenaClient }) => {
  const command = {};
  command.execute = sqlCommand => {
    const params = {
      QueryString: sqlCommand,
      QueryExecutionContext: {
        Database: process.env.ATHENA_DB || "default"
      }
    };
    return athenaClient.startQueryExecution(params).promise();
  };

  return command;
};

В моем тесте я издеваюсь над клиентом athena и внедряю его в функцию, а также хочу проверить, что метод startQueryExecution вызывается с sqlCommand, который отправляется в качестве ввода,Итак, я пытался создать заглушку на нем.

Это мой тест:

const AWS = require("aws-sdk");
const AWS_MOCK = require("aws-sdk-mock");
const sinon = require("sinon");
const expect = require("chai").expect;

describe("Executes a sql command in Athena", async done => {
  process.env.ATHENA_DB = "default";

  it("the sqlCommand is sent to startQueryExecution", async () => {
    const SQL_COMMAND = "DROP TABLE IF EXISTS dataset_test PURGE;";

    const athenaClient = {
      startQueryExecution: params => ({})
    };

    const executeAthenaQueryCommand = require("../commands/executeAthenaQueryCommand").init(
      {
        athenaClient
      }
    );

    sinon.stub(athenaClient, "startQueryExecution");
    sinon.stub(executeAthenaQueryCommand, "execute");

    const result = await executeAthenaQueryCommand.execute(SQL_COMMAND);

    sinon.assert.calledWith(executeAthenaQueryCommand.execute, SQL_COMMAND);

    const expectedResult = {
      QueryString: SQL_COMMAND,
      QueryExecutionContext: {
        Database: "default"
      }
    };

    sinon.assert.calledWith(athenaClient.startQueryExecution, expectedResult);
  });

  after(() => {});
});

Однако я получаю сообщение об ошибке:

   AssertError: expected startQueryExecution to be called with arguments 
    at Object.fail (node_modules/sinon/lib/sinon/assert.js:104:21)
    at failAssertion (node_modules/sinon/lib/sinon/assert.js:61:16)
    at Object.assert.(anonymous function) [as calledWith] (node_modules/sinon/lib/sinon/assert.js:86:13)
    at Context.it (test/executeAthenaQueryCommand.spec.js:37:22)
    at <anonymous>

Любойпомогите пожалуйста?

1 Ответ

0 голосов
/ 22 февраля 2019

Вы почти сделали это правильно.Некоторые примечания для исправления теста:

Добавление возврата в заглушку startQueryExecution

Это необходимо, чтобы функция execute выполнялась правильно для возврата обещания.

sinon.stub(athenaClient, "startQueryExecution").returns({ promise: () => Promise.resolve() });

Удалить заглушку для метода execute

Это реальный метод, который мы хотим протестировать, и мы вызываем его в следующей строке, поэтому мы не должны заглушать его,

sinon.stub(executeAthenaQueryCommand, "execute"); // remove this
sinon.assert.calledWith(executeAthenaQueryCommand.execute, SQL_COMMAND); // remove this

Итак, итоговый тестовый файл будет

describe("Executes a sql command in Athena", async done => {
  ...

  it("the sqlCommand is sent to startQueryExecution", async () => {
    ...

    sinon.stub(athenaClient, "startQueryExecution").returns({ promise: () => Promise.resolve() }); // add returns

    const result = await executeAthenaQueryCommand.execute(SQL_COMMAND);

    const expectedResult = {
      QueryString: SQL_COMMAND,
      QueryExecutionContext: {
        Database: "default"
      }
    };

    sinon.assert.calledWith(athenaClient.startQueryExecution, expectedResult);
  });

  after(() => {});
});
...