【问题标题】:Simulating keyboard events with JavaScript用 JavaScript 模拟键盘事件
【发布时间】:2021-02-28 00:29:03
【问题描述】:

如何模拟在 contenteditable 元素中输入一些文本? 我需要模拟一切,因为用户将事件将用于测试目的。 我可以通过以下方式触发事件:

node.dispatchEvent(new KeyboardEvent('keydown', {key: 'A'}))
node.dispatchEvent(new KeyboardEvent('keyup', {key: 'A'}))

但它不会打印A。所以我必须使用 API:

node.innerHTML += 'A'

但是光标会在不同的地方,所以我需要创建一个范围。

let r = document.createRange()
r.selectNodeContents(editor)
r.collapse(false)
let s = window.getSelection()!
s.removeAllRanges()
s.addRange(r)

模拟箭头呢?如何模拟向上箭头?也许有一些图书馆可以做到这一点?

【问题讨论】:

    标签: javascript testing automation


    【解决方案1】:

    Testing Library 是模拟用户交互的绝佳选择。它可以与配套库 user-event 配对,以模拟用户输入,例如单击、dblClick、向上/向下箭头、选项卡等。下面是一个在文本字段中模拟用户输入的示例:

    import { screen } from '@testing-library/dom';
    import userEvent from '@testing-library/user-event';
    
    test('type', () => {
      document.body.innerHTML = `<textarea />`;
    
      // type 'Hello' followed by the enter key, followed by 'World!' into the textarea
      userEvent.type(screen.getByRole('textbox'), 'Hello,{enter}World!');
      // We expect that textarea to now have the given value
      expect(screen.getByRole('textbox')).toHaveValue('Hello,\nWorld!');
    });
    

    您可以延迟输入,或在单击元素之前使用skipClick 选项进行输入(例如,在元素自动聚焦的情况下)。

    这里有很多例子:https://testing-library.com/docs/ecosystem-user-event/。它们还具有各种框架的包装器,例如 react、angular 和 puppeteer。因此,根据您使用的框架(或只是 vanilla js),您可以:

    1. 创建您的页面/组件
    2. 使用用户事件库模拟用户输入事件
    3. 断言您期望为真的某些条件

    我也非常喜欢该库可以轻松模拟服务器请求,这样我就可以全面测试组件,而无需担心其内部结构和结构。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-19
    • 1970-01-01
    • 1970-01-01
    • 2013-05-25
    • 1970-01-01
    • 2023-03-23
    • 2012-10-12
    • 1970-01-01
    相关资源
    最近更新 更多