首页 > 解决方案 > 在 TestCafe 中访问剪贴板

问题描述

如何访问 TestCafe 中的剪贴板?我无法使用 navigator.clipboard API,因为我们在无头 chrome --allow-insecure 中运行。(这不是我可以改变的)。

有任何想法吗?

谢谢!

标签: testinghttpsautomated-testse2e-testingtestcafe

解决方案


TestCafe 目前没有内置的剪贴板工具。但是,您可以使用客户端函数来模拟剪贴板:

import { Selector, ClientFunction } from 'testcafe';
fixture `Example`
    .page `http://devexpress.github.io/testcafe/example/`;

test('Clipboard test', async t => {
    const text = 'Value for copy-paste';

    const emulateClipboard = ClientFunction(() => {
        let buffer = '';

        document.addEventListener('keypress', event => {
            if (event.ctrlKey) {
                if (event.key === 'c')
                    buffer = document.getSelection().toString();
                
                if (event.key === 'v')
                    document.activeElement.value = buffer;
            }
        });
    });

    await emulateClipboard();
    await t
        .typeText('#developer-name', text)
        .selectText('#developer-name')
        .pressKey('ctrl+c')
        .click('#tried-test-cafe')
        .click('#comments')
        .pressKey('ctrl+v')
        .expect(Selector('#comments').value).eql(text)
});

此示例在 Chrome 中正常工作。由于访问 <textarea> 元素内容的不同,它可能无法在其他浏览器中运行。

您可以从这个讨论中收集更多信息:https ://github.com/DevExpress/testcafe/issues/2668


推荐阅读