我已经使用样板create-react-app创建了一个react应用。我正在尝试使用testing-library
编写基本测试,但是它们失败了。我有一个Login
组件,该组件使用Alert
组件显示错误消息。
这是我的Login
组件看起来像
function Login({ onSubmit, error }) {
const [credentials, setCredentials] = useState({
username: '',
password: ''
});
const onFieldChange = ({ value }, field) => {
let newCredentials = credentials;
newCredentials[field] = value;
setCredentials(newCredentials);
}
return (
<div className="container">
<h2 id="title">Login 👋</h2>
<form className="items" onSubmit={(event) => onSubmit(event, credentials)}>
<input type="text" id="username" placeholder="Username" onChange={({ target }) => onFieldChange(target, 'username')} />
<input type="password" id="password" placeholder="Password" onChange={({ target }) => onFieldChange(target, 'password')} />
{error && <Alert message={error} />}
<button id="button" data-testid="submit">Submit</button>
<a id="sign" type="submit" href="#">Sign Up</a>
</form>
</div>
);
}
export { Login };
警报组件
const AlertError = styled.div`
background-color: #f8d7da;
padding: 10px;
border-radius: 5px;
`
const AlertMessage = styled.p`
color: #721c24
`
const Container = styled.div(props => ({
display: 'flex',
flexDirection: props.column && 'column'
}))
function Alert({ message }) {
return (
<AlertError>
<AlertMessage role="alert" data-testid="alert">{message}</AlertMessage>
</AlertError>
)
}
App.test.js
describe('Login ', () => {
let changeUsernameInput, changePasswordInput, clickSubmit, handleSubmit, alertRender;
const { container, getByTestId, getByText, getByPlaceholderText, getByRole } = render(<Login onSubmit={handleSubmit} error={''} />);
const user = { username: 'michelle', password: 'smith' }
fireEvent.change(getByPlaceholderText(/username/i), { target: { value: user.username } })
fireEvent.change(getByPlaceholderText(/password/i), { target: { value: user.password } })
alertRender = getByRole('alert') // breaks on this line
it('should call onSubmit with the username and password', () => {
expect(true).toBeTruthy()
})
})
以下是我收到的错误Unable to find an accessible element with the role "alert"
据我所知,<Alert />
组件不可见,因为error
设置为空字符串,因此为假。
写作时
error && <Alert message={error} />
仅在设置错误时显示<Alert />
。据我所知,您没有更改error
。
React Testing Library中的getBy*
选择器会出现恐慌,如果该项目不存在。如果您不想这样做,可以改用queryBy*
。或者,您可以为error
输入非空值。我不确定您要测试什么。