我正在开始使用这些技术(包括 Javascript)的旅程,所以,这是一个初学者问题。我正在努力弄清楚如何断言 HTML 属性中的给定文本符合预期。
HTML 片段:
<input name="8hv3a" type="radio" id="email-optout-8hv3a" value="1|optin|out" data-com.user-edited="yes">
到目前为止,这是我的 .it 函数,使用 Mochai、Puppeteer 和 Chai(为清楚起见省略了设置和拆卸:
it('opt out of email', async function () {
await page.setDefaultNavigationTimeout();
await page.waitForSelector('.widget-title');
const frame = page.frames().find(frame => frame.name() === 'iframe');
const emailOptOutButton = await frame.$('#email-optout-8hv3a');
await emailOptOutButton.click();
const emailOptOutConfirmedValue = await frame.$('#email-optout-8hv3a', e => e.getAttribute('data-com.user-edited'))
expect(emailOptOutConfirmedValue).to.include('yes')
})
点击事件之前一切正常,但我的断言显然是错误的。错误是:
AssertionError: object tested must be an array, a map, an object, a set, a string, or a weakset, but object given
我试过了
it('opt out of email', async function () {
await page.setDefaultNavigationTimeout();
await page.waitForSelector('.widget-title');
const frame = page.frames().find(frame => frame.name() === 'iframe');
const emailOptOutButton = await frame.$('#email-optout-8hv3a');
await emailOptOutButton.click();
await page.$eval.emailOptOutConfirmedValue.getAttribute('data-com.user-edited')
expect(emailOptOutConfirmedValue).to.include('yes')
})
给出:
TypeError: Cannot read property 'getAttribute' of undefined
还有:
it('opt out of email', async function () {
await page.setDefaultNavigationTimeout();
await page.waitForSelector('.widget-title');
const frame = page.frames().find(frame => frame.name() === 'iframe');
const emailOptOutButton = await frame.$('#email-optout-8hv3a');
await emailOptOutButton.click();
const emailOptOutConfirmedValue = await frame.$('#email-optout-8hv3a', e => e.getAttribute('data-com.user-edited'))
assert.equal(emailOptOutConfirmedValue, 'yes')
})
给出:
ReferenceError: assert is not defined
正如我所说,我是初学者,所以感谢您的帮助!
最佳答案
这段代码是错误的:
const emailOptOutConfirmedValue = await frame.$('#email-optout-8hv3a', e => e.getAttribute('data-com.user-edited'))
expect(emailOptOutConfirmedValue).to.include('yes')
您正在使用 frame.$(selector)
.注意它是如何只接受一个参数的。第二个参数被忽略,你的调用返回一个 DOM 元素的句柄,这导致 expect(...).to.include(...)
失败并提示它无法测试那个东西。
你应该使用 frame.$eval(selector, pageFunction[, ...args])
反而。此调用将调用作为应用选择器结果的第二个参数传递的函数。所以代码应该是:
const emailOptOutConfirmedValue = await frame.$eval('#email-optout-8hv3a', e => e.getAttribute('data-com.user-edited'))
expect(emailOptOutConfirmedValue).to.include('yes')
我在上面保留了你的测试,但在我看来你在这里寻找的是属性的特定值,所以我会使用这个测试:
expect(emailOptOutConfirmedValue).to.equal('yes')
如果属性的值为 baryesfoo
,则包含测试将通过。
关于javascript - 使用 Puppeteer、Mocha 和 Chai 断言 html 标签属性中存在文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53141002/