reactjs - 如何使用 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调用
解决方案
你如何redirect
在你的源代码中做到这一点?你在用react-router
吗?(在这种情况下,您可以简单地模拟重定向函数并检查它是否已被调用!?)
请查看此相关问题:使用 React 测试库提交后测试重定向
Kent C Dodds 正在此视频中构建和测试一个简单的登录组件(从时间戳 14:30 开始): https ://www.youtube.com/watch?v=eg_TFYF_cKM&t=869s&ab_channel=Applitools%3AVisualAIPoweredTestAutomation
推荐阅读
- python - 如何从回复 ID(Python)中获取线程/对话?
- ios - 当观察到可能发布在“用于注册观察者的线程之外的线程上”的通知时,如何确保线程安全的 UI 工作?
- c# - 更改嵌套节点的值
- reactjs - 来自 Dockerfile 的值可在 Sources 选项卡中搜索 - 如何保护环境变量?
- python - Python JSON API 打印字典内的列表
- batch-file - windows下python虚拟环境发送命令
- c# - 如何在 C# 中播放 .wav 文件
- reactjs - 你不应该在外面使用
- 从不同的文件夹导入 - python - 使用字典元组键的最后两个元素求和
- python - Jupyter 在 VSCode 中运行错误的单元格