概述

自 v2.2 起,Nightwatch 允許您監聽網站執行期間發生的 JavaScript 例外,並透過回呼函式將其提供給測試本身。

這是透過 Selenium 4 中現在提供的 Chrome DevTools 通訊協定支援 來實現的。

`captureBrowserExceptions()` 命令僅適用於基於 Chromium 的瀏覽器,例如 Google Chrome 和 Microsoft Edge。

捕捉 JS 例外

在導覽至您的網站之前,請使用具有必要參數的 browser.captureBrowserExceptions() 命令。

captureBrowserExceptions() 接受一個回呼函式,每當擲出新的 Error 時,它會收到一個 event 物件作為引數。接收到的 event 物件規格如下

名稱 類型 描述
時間戳記 數字 捕捉到 JS 例外的時間。
exceptionDetails
物件 具有發生例外之所有詳細資訊的 JS 物件。
物件的規格可以從此處讀取。

範例

tests/catch-js-exceptions.js
describe('catch browser exceptions', function() {
  it('captures the js exceptions thrown in the browser', async function() {
    await browser.captureBrowserExceptions((event) => {
      console.log('>>> Exception:', event);
    });
    
await browser.navigateTo('https://duckduckgo.com/');
const searchBoxElement = await browser.findElement('input[name=q]'); await browser.executeScript(function(_searchBoxElement) { _searchBoxElement.setAttribute('onclick', 'throw new Error("Hello world!")'); }, [searchBoxElement]);
await browser.elementIdClick(searchBoxElement.getId()); }); });

上方範例的輸出

  Running captureBrowserExceptions():
───────────────────────────────────────────────────────────────────────────────────────────────────
{
  exceptionDetails: {
    exceptionId: 1,
    text: 'Uncaught',
    lineNumber: 0,
    columnNumber: 6,
    scriptId: '55',
    url: 'https://duckduckgo.com/',
    stackTrace: { callFrames: [Array] },
    exception: {
      type: 'object',
      subtype: 'error',
      className: 'Error',
      description: 'Error: Hello world!\n' +
        '    at HTMLAnchorElement.onclick (https://duckduckgo.com/:1:7)',
      objectId: '6711588812373266697.1.1',
      preview: [Object]
    },
    executionContextId: 1
  },
  timestamp: 2022-06-10T13:14:52.722Z
}
No assertions ran.