首页 > 解决方案 > 如何使用 jest 和 react 测试库测试登录组件

问题描述

我尝试为登录组件创建集成测试,但我面临一些问题。基本上我需要检查在输入电子邮件和密码凭据并单击提交按钮后,它会将我重定向到给定页面。我waitForComponentToBeRemoved用来检查登录组件的电子邮件或密码字段是否不存在,但出现错误:

Timed out in waitForElementToBeRemoved.

如果我没有正确的方法或者您需要更多信息,请告诉我。

这是测试:

    it( 'Login with real username and password', async () => {



        beforeEach(() => {
            fetch.dontMock()
        })


        act(() => {
            ReactDOM.render(<App />, container);
        })

        // log /
        console.log('history', window.location.pathname)

        const email = process.env.TEST_EMAIL
        const password = process.env.TEST_PASSWORD

        const signInButton = screen.getByTestId('landing-signin')

        fireEvent.click(signInButton)


        await waitFor(async () => {
            expect(signInButton).not.toBeInTheDocument()

            // log /signin
            console.log('history', window.location.pathname)
        })

        
        const emailField = screen.getByPlaceholderText('Email address')

        const passwordField = screen.getByPlaceholderText('Your password')
        const button = screen.getByTestId('submit-button')

        expect(button).toBeInTheDocument()
        expect(passwordField).toBeInTheDocument()
        expect(emailField).toBeInTheDocument()

        userEvent.type(emailField, email)
        userEvent.type(passwordField, password)


        await act(async () => {

            fireEvent.click(button)

        })

        // Timed out in waitForElementToBeRemoved.
        await waitForElementToBeRemoved(button).then(() => {

            console.log('element has been removed')
        })

        // i need something to wait the response and the redirection to be done

    })

ps:我不想模拟数据,它需要做真正的api调用

标签: reactjsjestjsreact-testing-library

解决方案


你如何redirect在你的源代码中做到这一点?你在用react-router吗?(在这种情况下,您可以简单地模拟重定向函数并检查它是否已被调用!?)

请查看此相关问题:使用 React 测试库提交后测试重定向

Kent C Dodds 正在此视频中构建和测试一个简单的登录组件(从时间戳 14:30 开始): https ://www.youtube.com/watch?v=eg_TFYF_cKM&t=869s&ab_channel=Applitools%3AVisualAIPoweredTestAutomation


推荐阅读