首页 > 解决方案 > 如何使用 Jest 从另一个元素的输入测试一个元素的输出?

问题描述

我的测试试图模拟用户在文本区域中输入“abcdef”作为输入,然后验证输出中是否写入了相同的字符串(“abcdef”):

it("should write in input and correspond in output", async () => {
    render(App);

    const input = document.getElementById("input");
    fireEvent.change(input, { target: { value: 'abcdef' }})
    
    let output = document.getElementById("output");
    expect(output).toHaveTextContent("abcdef"); // undefined
});

这是输出元素:

    <h1 id="output">{output}</h1>

如果我在 {output} 标记旁边硬编码“abcdef”,那么我的测试通过,但fireEvent.change似乎无法正常工作。也许我误解了 Jest 的功能 - 也许它只进行单元测试,而不是用户测试/端到端测试?

标签: jestjssvelte

解决方案


fireEvent.change(input, { target: { value: 'abcdef' }})

应该有一个await

await fireEvent.change(input, { target: { value: 'abcdef' }})

它有效!

it("should write in input and correspond in output", async () => {
    render(App);
    const input = document.getElementById("input");
    fireEvent.change(input, { target: { value: 'abcdef' }})
    let output = document.getElementById("output");
    expect(output).toHaveTextContent("abcdef");
});

结果:✓ 应写入输入并对应输出(3 ms)


推荐阅读