簡體   English   中英

NodeJS - 回調 function 中的斷言沒有失敗 Mocha 單元測試

[英]NodeJS - Assertion in callback function not failing Mocha unit test

我正在嘗試在 NodeJS 應用程序上運行 Mocha 單元測試,但在處理回調 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;
        });
    });
});

當單元測試運行時,我故意制作manipuldatedPdf null 來驗證斷言是否有效。

斷言比較成功完成,但單元測試顯示為通過測試並打印出與未處理的 promise 拒絕相關的警告:

(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的回調 function 中引發的任何異常,但在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)));
    });
});

有沒有辦法處理這些斷言失敗使單元測試失敗?

在回調中進行斷言時,您應該使用 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)
      }
    });
  });
});

暫無
暫無

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

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