NodeJS - Утверждение в функции обратного вызова не дает сбой модульного теста Mocha - PullRequest
0 голосов
/ 06 августа 2020

Я пытаюсь запустить модульные тесты Mocha в приложении NodeJS, но у меня проблемы с обработкой утверждений внутри функции обратного вызова.

Например, у меня есть следующий модульный тест:

describe('PDF manipulation', () => {
    it('Manipulated test file should not be null', async () => {
        fs.readFile('test.pdf', async function (err, data){
            if (err) throw err;
            let manipulatedPdf = await manipulate_file(data);
            expect(manipulatedPdf).to.be.not.null;
        });
    });
});

При запуске модульного теста я намеренно делаю manipuldatedPdf нулевым, чтобы убедиться, что утверждение работает.

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

(node:13492) UnhandledPromiseRejectionWarning: AssertionError: expected null not to be null
    at ...
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:13492) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:13492) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

При попытке решить проблему, похоже, мне нужно иметь возможность .catch() любых исключений, возникающих внутри функции обратного вызова readFile , но добавив что-то вроде следующих результатов в TypeError: (intermediate value).catch is not a function:

describe('PDF manipulation', () => {
    it('Manipulated test file should not be null', async () => {
        fs.readFile('test.pdf', (async function (err, data){
            if (err) throw err;
            let manipulatedPdf = await manipulate_file(data);
            expect(manipulatedPdf).to.be.not.null;
        }).catch(error => console.log(error)));
    });
});

Есть ли способ справиться с этими ошибками утверждения, чтобы сделать модульный тест неудачным?

1 Ответ

1 голос
/ 06 августа 2020

Вы должны использовать обратный вызов mocha done при выполнении утверждений в обратном вызове. Done обратный вызов принимает ошибку в качестве первого аргумента, поэтому имеет смысл заключить утверждение в блок try / catch, чтобы получить значимую ошибку, когда утверждение не выполняется:

describe('PDF manipulation', () => {
  it('Manipulated test file should not be null', (done) => {
    fs.readFile('test.pdf', async function (err, data){
      if (err) throw err;
      let manipulatedPdf = await manipulate_file(data);
      try {
        expect(manipulatedPdf).to.be.not.null;
        done()
      } catch (err) {
        done(err)
      }
    });
  });
});
...