在 Nightwatch 中偵錯元件測試
概述
在 Nightwatch 中偵錯元件測試不像偵錯一般的 Node.js 應用程式或服務那樣直接,因為 Nightwatch 需要將程式碼注入瀏覽器以呈現元件。
但是,自 Nightwatch v2.4 以來,我們提供了幾種使用瀏覽器開發人員工具主控台檢查和偵錯已掛載元件的方法。
預覽元件
Nightwatch 提供了在預覽模式下執行元件測試的功能(使用 --preview
CLI 引數),這只會開啟 Vite 測試渲染器並無限期地暫停執行。
這在開發期間很有用,因為 Vite 渲染器能夠透過其內建的熱模組替換 (HMR) 功能自動重新載入元件。
您可以使用 Nightwatch 內建的平行處理功能,在 Firefox 和 Chrome 中同時開啟故事
偵錯元件
除了預覽故事之外,還可以使用 Nightwatch 來偵錯故事。以下是如何執行此操作:
- 傳遞
--debug
和--devtools
CLI 旗標 – 這會在元件呈現後立即注入.debug()
命令 - 使用
debugger
陳述式在play()
函式內部新增中斷點。
範例 (React)
在下面的範例中,我們使用 debugger
來使用瀏覽器開發人員工具偵錯 play()
函式。此功能目前可在 Chrome、Edge 和 Safari 中使用。
此範例以安裝了 @nightwatch/storybook
外掛程式的 Storybook 專案為基礎。有關詳細資訊,請參閱Storybook 整合頁面。
Form.stories.jsx
import { userEvent, within } from '@storybook/testing-library';
import Form from './Form.jsx';
export default {
title: 'Form',
component: Form,
}
const Template = (args) => <Form {...args} />
// Component story for an empty form
export const EmptyForm = Template.bind({});
// Component story simulating filling in the form
export const FilledForm = Template.bind({});
FilledForm.play = async ({ canvasElement }) => {
// Starts querying the component from its root element
const canvas = within(canvasElement);
debugger;
// 👇 Simulate interactions with the component
await userEvent.type(canvas.getByTestId('new-todo-input'), 'outdoors hike');
await userEvent.click(canvas.getByRole('button'));
};
FilledForm.test = async (browser, { component }) => {
// 👇 Run commands and assertions in the Nightwatch context
await expect(component).to.be.visible;
}
執行範例並在 Chrome 開發人員工具主控台中觀察中斷點。
您也可以使用整合式偵錯主控台從 Nightwatch 發出命令。