反应测试库中的测试失败

时间:2020-05-10 18:47:52

标签: javascript reactjs jestjs react-testing-library

我已经使用样板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 } })
  fireEvent.click(getByText(/submit/i))
  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"

更新
如@Christian所提到的,当我尝试error的值时,Login组件中的get属性没有填充,因此我仅在提交表单后才对其进行查询。这是完整的更新后的测试文件。

describe('Login ', () => {
  let changeUsernameInput, changePasswordInput, clickSubmit, handleSubmit, alertRender, error;
  handleSubmit = jest.fn()
  const { getByTestId, getByPlaceholderText, queryByTestId, rerender } = render(<Login onSubmit={handleSubmit} error={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 } })
  // fireEvent.click(getByText(/submit/i))
  fireEvent.submit(getByTestId(/login-form/i))

  // re-render the same component with different props
  error = 'The username and password you entered did not match our records. Please double-check and try again.'
  rerender(<Login onSubmit={handleSubmit} error={error} />)
  alertRender = queryByTestId('alert')
  console.log("alertRender:", alertRender.textContent)
  it('should call onSubmit with the username and password', () => {
    expect(alertRender.textContent).toBe(error)
  })
})

1 个答案:

答案 0 :(得分:1)

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

写作时

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

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

如果该项目不存在,则来自React Testing Library的getBy*选择器会出现混乱。 如果您不想这样做,可以改用queryBy*。或者,您可以为error传递非空值。我不确定你想要什么。