【问题标题】:Setting attribute via a ClientScript not persisting通过 ClientScript 设置属性不持久
【发布时间】:2020-04-04 17:11:16
【问题描述】:

我的夹具有一个 ClientScript 设置元素的属性(该元素来自执行document.querySelectorAll(...) 的脚本):

element.setAttribute("data-foo", 'foo');

稍后在 testcafe-land 中,当我尝试使用 Selector 访问该元素时,它始终是 null

const element = await Selector('[data-foo="foo"]')();

我在注入的 ClientScript 中插入了 debugger 语句,当我逐步执行该函数时,我看到该元素确实添加了属性,但只要我让执行继续并尝试在devtools 控制台属性已从元素中消失。

我 - 认为 - 它与 iframe/shadow DOM 有关吗? testcafe 正在创建?我看到 chrome devtools 中有一个子 iframe/执行上下文 - 我的 ClientScript 被注入到 window.top 但也有一个 testcafe-created iframe

有什么想法可以让它发挥作用吗?我想要一个注入的脚本来操作 DOM(通过添加一个属性),稍后我想要一个 testcafe Selector 来选择。为什么这不起作用,我怎样才能让它起作用??? 谢谢!!! 标记

【问题讨论】:

    标签: testing automation automated-tests e2e-testing testcafe


    【解决方案1】:

    TestCafe injects custom scripts into the head tag。这些脚本在加载 DOM 之前执行。

    以下是如何使用客户端脚本操作 DOM 的示例:

    import { Selector } from 'testcafe';
    
    const scriptContent = `
    window.addEventListener('DOMContentLoaded', function () {
        var p = document.querySelector('p');
        
        p.setAttribute("data-foo", 'foo');
    });
    `;
    
    fixture `My fixture`
        .page('https://devexpress.github.io/testcafe/example/')
        .clientScripts({ content: scriptContent });
    
    test('My test', async t => {
        const el = await Selector('[data-foo="foo"]');
    
        await t
            .expect(el.textContent).eql('This webpage is used as a sample in TestCafe tutorials.');
    });
    

    【讨论】:

      猜你喜欢
      • 2012-07-26
      • 1970-01-01
      • 1970-01-01
      • 2011-06-30
      • 2021-02-17
      • 1970-01-01
      • 1970-01-01
      • 2011-05-19
      • 2016-06-11
      相关资源
      最近更新 更多