跳到主要内容

Nightwatch Testing Library

nightwatch-testing-library 允许在 Nightwatch 中使用 dom-testing-library 查询来进行端到端的 web 测试。

安装

请务必先按照 Nightwatch 的安装和配置说明 进行操作。

然后就

npm install -D @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('http://localhost: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('http://localhost: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')
},
}