状态更改后,React Test 无法按文本查找元素

问题描述

我有一个 LoginForm 组件,它接受 login 回调并呈现登录表单。 当 login 返回一个被拒绝的承诺时,消息会显示在组件中。 这是我要测试的行为。

我正在使用带有 jestenzyme@testing-library/react 的 create-react-app 环境。

我已经在 UI(浏览器)中手动测试了该组件,并确保它可以正常工作并显示消息,但测试无效且最后一个断言失败:

TestingLibraryElementError: Unable to find an element with the text: There was an error. 
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.

在浏览器中呈现时,我检查了消息,它显示文字“发生错误”,中间没有任何元素。仅由样式组件包装。 我无法进行测试,有人可以帮忙吗?

我的测试如下:

    it("should display error text in login form when login fails",async () => {
        const errorText = "There was an error";
        const login = jest.fn(() => {
            return Promise.reject(errorText);
        });

        const result = render(<LoginForm login={login} />);


        const form = result.container.querySelector("form");
        const email = await result.findByLabelText("Email");
        const password = await result.findByLabelText("Password");

        fireEvent.change(email,{target: {name: "email",value: "1"}});
        fireEvent.change(password,{target: {name: "password",value: "1"}});

        expect(form).tobedefined();

        fireEvent.submit(form!,{});

        expect(login).toBeCalledTimes(1);
 
        // This assertion fails
        expect(result.getByText(errorText)).toBeInTheDocument();
    });

我的组件渲染如下:

render() {
        const {error,email,password} = this.state;

        return (
            <Form novalidate onSubmit={this.onSubmit}>
                <InputWrapper>
                    <Label htmlFor="email">Email</Label>
                    <InputEmail id="email" name="email" value={email} onChange={this.onChange}/>
                </InputWrapper>

                <InputWrapper>
                    <Label htmlFor="password">Password</Label>
                    <InputPassword id="password" name="password" value={password} onChange={this.onChange}/>
                </InputWrapper>

                // LoginError is a styled-component
                {error && (<LoginError>{error}</LoginError>)}

                {this.props.children}

                <Button>Login</Button>
            </Form>
        );


    }

解决方法

在 fireEvent.submit(form!,{}); 之后尝试使用 wait 或 waitFor 方法;等待承诺的解决和重新渲染发生。

参考:testing-library.com/docs/dom-testing-library/api-async#waitfor