我如何使用 Jest 从另一个元素的输入测试一个元素的输出?

How do I use Jest to test the output in one element, from an input from another element?

我的测试试图模拟用户在文本区域中键入“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 的功能 - 也许它只进行单元测试,而不进行用户测试/端到端测试?

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 毫秒)