我正在尝试第一次反应单元测试。我正在尝试在提交表单后测试重定向到页面。但它返回一个错误,并且链接从未改变。所以对于测试,我填写了两个输入,email
然后password
单击按钮,它应该重定向到/profile
它收到的页面/
。
我就是这样做的。
let container : HTMLDivElement
beforeEach(() => {
container = document.createElement('div')
document.body.appendChild(container)
ReactDOM.render(
<MemoryRouter>
<Login />
</MemoryRouter>, container)
})
afterEach(() => {
document.body.removeChild(container)
container.remove()
})
const setup = () => {
const rend = render(
<MemoryRouter>
<Login />
</MemoryRouter>)
const input = container.querySelectorAll('input')
const label = container.querySelector('label')
return {
input,
label,
...rend,
}
}
it('Redirect to profile after login', () => {
const history = createMemoryHistory()
render(
<Router history={history}>
<Login />
</Router>
);
const { input } = setup()
fireEvent.change(input[0], {target: {value: 'test@toto'}})
fireEvent.change(input[1], {target: {value: '15fezfzeoier'}})
userEvent.click(getByTestId(container, 'login-btnCheck'))
expect(history.location.pathname).toBe("/profile")
})
})
这是登录组件
import React, { useState } from 'react'
import Logo from '../assets/appiness.svg'
import { loginCheck } from './request/Request'
import { Link } from 'react-router-dom'
export const Login = () => {
const [username, setUsername] = useState<string>("")
const [password, setpPassword] = useState<string>("")
const [error, setError] = useState<string>("")
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault()
loginCheck({username, password, setError})
// request here
}
return (
<div className="bg-appiness-blue h-screen flex flex-col items-center justify-center">
<img src={Logo} alt="logo" className="w-64 mb-1" />
<h1 className="text-white font-semibold text-3xl mb-7">App'Iness</h1>
<form data-test="forms-login" className="flex mb-3" onSubmit={handleSubmit}>
<div className="flex flex-col space-y-0.5">
<input name="login" placeholder="Username" className="w-64 rounded-md focus:outline-none p-2" type="text" onChange={(e: React.ChangeEvent<HTMLInputElement>) => setUsername(e.target.value)} />
<input name="password" placeholder="Password" className="w-64 rounded-md focus:outline-none p-2" type="password" onChange={(e: React.ChangeEvent<HTMLInputElement>) => setpPassword(e.target.value)} />
</div>
<button data-testid="login-btnCheck" type="submit" className="bg-appiness-orange rounded-md">
<i className="fas fa-arrow-right w-12 text-2xl rounded-md text-white bg-appiness-orange" />
</button>
</form>
<div className="space-y-3 flex flex-col items-center">
{error}
<h6 className={`${error.length !== 0 ? 'block' : 'hidden'}text-appiness-darkblue text-xs`}>Forgot password</h6>
<Link to="/register">
<button className="bg-appiness-darkblue w-28 h-8 rounded-xl text-white focus:outline-none">Sign Up</button>
</Link>
</div>
</div>
)
}