javascript – 使用Puppeteer,Mocha和Chai在html标记属性中断言文本的存在

我开始使用这些技术(包括Javascript),所以,一个初学者的问题.我正在努力弄清楚如何断言HTML属性中的给定文本是否符合预期.

HTML代码段:

dio" 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,则包含测试将通过.

相关文章

vue阻止冒泡事件 阻止点击事件的执行 <div @click=&a...
尝试过使用网友说的API接口获取 找到的都是失效了 暂时就使用...
后台我拿的数据是这样的格式: [ {id:1 , parentId: 0, name:...
JAVA下载文件防重复点击,防止多次下载请求,Cookie方式快速简...
Mip是什么意思以及作用有哪些