0

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

我将 create-react-app 环境与jest,enzyme@testing-library/react.

我已经在 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>
        );


    }
4

1 回答 1

3

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

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

于 2021-05-14T19:15:30.523 回答