【问题标题】:tests failing in react testing library在反应测试库中测试失败
【发布时间】:2020-05-12 07:03:51
【问题描述】:

我使用样板 create-react-app 创建了一个反应应用程序。我正在尝试使用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 所提到的,问题是当我尝试get 其值时,登录组件中的error 道具未填充,因此我只能在提交表单后查询它。这是完整更新的测试文件。

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)
  })
})

【问题讨论】:

    标签: javascript reactjs jestjs react-testing-library


    【解决方案1】:

    据我所知,&lt;Alert /&gt; 组件不可见,因为error 设置为空白字符串,因此是错误的。

    当你写作时

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

    &lt;Alert /&gt; 仅在设置错误时显示。 据我所知,你并没有改变error

    如果项目不存在,来自 React 测试库的 getBy* 选择器会出现恐慌。 如果您不希望这样,您可以改用queryBy*。或者您可以为error 传递一个非空值。我不确定你想要什么。

    【讨论】:

    • 感谢克里斯蒂安的回复。啊!在查询警报之前,我忘记在此处添加fireEvent.click 行。我已经更新了问题,请看一下。此外,我必须使用更新的道具重新渲染组件,因为在“提交”之后,道具会更新并且现在可以正常工作。再次感谢
    • 我很高兴你能成功。不过,我认为您的测试名称有点误导。 it('should call onSubmit...') 应该重命名为 it('shows the error if there is one'),如果你想保持相同的内容。要检查 onSubmit 是否被调用,可以使用 Jest 的 expect(handleSubmit).toHaveBeenCalled()
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-21
    相关资源
    最近更新 更多