反应测试库中的测试失败

问题描述 投票:0回答:1

我已经使用样板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"

javascript reactjs jest react-testing-library
1个回答
0
投票

据我所知,<Alert />组件不可见,因为error设置为空字符串,因此为假。

写作时

error && <Alert message={error} />

仅在设置错误时显示<Alert />。据我所知,您没有更改error

React Testing Library中的getBy*选择器会出现恐慌,如果该项目不存在。如果您不想这样做,可以改用queryBy*。或者,您可以为error输入非空值。我不确定您要测试什么。

© www.soinside.com 2019 - 2024. All rights reserved.