如果使用 useState 有条件地显示文本,如何使用 JEST 编写单元测试用例

How to write unit testcase using JEST if text shown conditionally with useState

sample.js


const Sample = () => {
    const [show, setShow] = useState(false);
    const onShow = () => {
        setShow(!show);
    }
    return(
        <div>
            <button onClick={onShow}>{show ? 'Hide Text' : 'Show text'}</button>
            {show && <label>Welcome!!</label>}
        </div>
    );
};
export default Sample;

Sample.test.js

import Sample from '../components/sample';
import React from "react";


test('render Sample text matcher', () => {
    render(<Sample />);
    const titleElement = screen.getByText(/Welcome!!/)
    expect(titleElement).toBeInTheDocument;
})

它抛出以下错误。如果元素呈现状态值,我该如何编写测试用例?

TestingLibraryElementError: Unable to find an element with the text: /Welcome!!/. This could be because the text is broken up by multiple elements. In this case, you can provide a function for your text matcher to make your matcher more flexible.

作为变通方法,在渲染之后您可以尝试点击激活显示的按钮:

document.querySelector('button').click();

您需要先点击您的按钮。否则 show 为假,不显示文本。

您可以使用:

const button = screen.getByRole('button');
fireEvent.click(button); // import this from react-testing-library