跳至主要內容

Nightwatch 測試函式庫

nightwatch-testing-library 允許在 Nightwatch 中使用 dom-testing-library 查詢,以進行端對端網頁測試。

安裝

請務必先遵循 Nightwatch 的安裝與設定說明

然後直接

npm install --save-dev @testing-library/nightwatch

請先閱讀此處

在其核心,nightwatch-testing-library 在 dom-testing-library 查詢和 CSS 選擇器之間進行轉換。這是因為 Nightwatch 遵循 WebDriver 標準的 定位器策略。目前,這意味著日誌中會有非常詳細的 CSS 路徑。歡迎提交 PR 來使用 自訂報告器 來解決這個問題 🤗。

所以請記住,NWTL 查詢的結果是 WebDriver 定位器,而不是 DOM 節點。

請注意,在 NWTL 中,所有查詢都必須使用 await

用法

const {getQueriesFrom} = require('@testing-library/nightwatch')

module.exports = {
beforeEach(browser, done) {
browser.url('https://127.0.0.1:13370')
done()
},

async getByLabelText(browser) {
const {getByLabelText} = getQueriesFrom(browser)

const input = await getByLabelText('Label Text')
browser.setValue(input, '@TL FTW')

browser.expect.element(input).value.to.equal('@TL FTW')
},

async getByAltText(browser) {
const {getByAltText} = getQueriesFrom(browser)
const image = await getByAltText('Image Alt Text')

browser.click(image)
browser.expect
.element(image)
.to.have.css('border')
.which.equals('5px solid rgb(255, 0, 0)')
},
}

AllBy 查詢

AllBy 查詢的結果會額外新增一個函數:nth,可以在 nightwatch 函數以及 NWTL 的 within 函數中使用。


async 'getAllByText - regex'(browser) {
const { getAllByText } = getQueriesFrom(browser);
const chans = await getAllByText(/Jackie Chan/)


browser.expect.elements(chans).count.to.equal(2)

const firstChan = chans.nth(0);
const secondChan = chans.nth(1);


browser.click(chans.nth(0));
browser.click(chans.nth(1));

browser.expect.element(secondChan).text.to.equal('Jackie Kicked');
browser.expect.element(firstChan).text.to.equal('Jackie Kicked');

},

設定

您可以像 dom-testing-library 一樣,使用 configure 函數自訂 testIdAttribute。

const {configure} = require('@testing-library/nightwatch')

configure({testIdAttribute: 'data-automation-id'})

容器

預設情況下,查詢會預先綁定到 document.body,因此無需提供容器。但是,如果您想使用容器限制查詢,可以使用 within

使用 within 的範例

const {getQueriesFrom, within} = require('@testing-library/nightwatch')

module.exports = {
beforeEach(browser, done) {
browser.url('https://127.0.0.1:13370')
done()
},
async 'getByText within container'(browser) {
const {getByTestId} = getQueriesFrom(browser)

const nested = await getByTestId('nested')
const button = await within(nested).getByText('Button Text')

browser.click(button)
browser.expect.element(button).text.to.equal('Button Clicked')
},
}