在调用fireEvent之后,waitForEvent找不到DOM更改

时间:2019-05-05 12:28:48

标签: react-testing-library

我要使用react-testing-library尝试测试以下组件:

MHD_RESPMEM_MUST_COPY

这完全符合生产中的预期目的。如果用户单击该按钮,则它将调用const PasswordIconButton = ({ stateString }) => { const { state, dispatch } = useContext(Store); const showPassword = getObjectValue(stateString, state); const toggleShowPassword = event => { event.preventDefault(); dispatch(toggleBoolean(stateString, !showPassword)); }; return ( <Layout showPassword={showPassword} toggleShowPassword={toggleShowPassword} /> ); }; export default PasswordIconButton; const Layout = ({ showPassword, toggleShowPassword }) => { return ( <IconButton onClick={toggleShowPassword} data-testid="iconButton"> {showPassword ? ( <HidePasswordIcon data-testid="hidePasswordIcon" /> ) : ( <ShowPasswordIcon data-testid="showPasswordIcon" /> )} </IconButton> ); }; ,它会切换布尔常量toggleShowPassword()的值。

如果showPassword等于false并且用户单击按钮,则可以看到showPassword被删除并出现<ShowPasswordIcon />。两者都设置了正确的<HidePasswordIcon />属性。

我正在尝试对该组件进行以下测试:

data-testid

import React from "react"; import { render, cleanup, fireEvent, waitForElement } from "react-testing-library"; import PasswordIconButton from "./PasswordIconButton"; afterEach(cleanup); const mockProps = { stateString: "signUpForm.fields.password.showPassword" }; describe("<PasswordIconButtonIcon />", () => { it("renders as snapshot", () => { const { asFragment } = render(<PasswordIconButton {...mockProps} />); expect(asFragment()).toMatchSnapshot(); }); // // ISSUE IS WITH THIS TEST: // :::::::::::::::::::::::::: it("shows 'hide password' icon on first click", async () => { const { container, getByTestId } = render( <PasswordIconButton {...mockProps} /> ); const icon = getByTestId("iconButton"); fireEvent.click(icon); const hidePasswordIconTestId = await waitForElement( () => getByTestId("hidePasswordIcon"), { container } ); expect(hidePasswordIconTestId).not.toBeNull(); }); }); 测试始终失败,我不确定为什么。 shows 'hide password' icon on first click绝对正确,并且可以在生产中完美运行。

我在这里想念什么?

1 个答案:

答案 0 :(得分:0)

我发现了...问题是我需要将组件包装在上下文提供程序中,因为如果没有const { state, dispatch } = useContext(Store);,它将无法正常工作。

所以我将渲染更改为:

    const { container, getByTestId } = render(
      <StateProvider>
        <PasswordIconButton {...mockProps} />
      </StateProvider>
    );`

现在测试通过了。