不幸的是,我的一个测试揭示了我对如何使用react-testing-library测试这个React web应用程序的一些严重误解。测试:
const setup = () => {
const utils = render(<UnderConstruction />)
const input = utils.getByLabelText('Email')
return {
input,
...utils,
}
}
test('It should set the email input', () => {
const { input } = setup();
const element = input as HTMLInputElement;
fireEvent.change(element, { target: { value: 'abc@def' } });
console.log(element.value);
expect(element.value).toBe('abc@def');
})这个简单的组件(使用marterial-ui)看起来像(为简洁起见,我删除了它的大部分):
<form noValidate autoComplete="off" onSubmit={handleSubmit}>
<TextField
id="email-notification"
name="email-notification"
label="Email"
value={email}
onInput={(e: React.FormEvent<EventTarget>) => {
let target = e.target as HTMLInputElement;
setEmail(target.value);
}}
placeholder="Email" />
<Button
type="submit"
variant="contained"
color="secondary"
>
Submit
</Button>
</form>第一个角色是为了让TypeScript高兴。第二个主要是关于我使用fireEvent来模拟用户输入。你对如何测试这个功能有什么想法吗?现在,测试总是失败,因为它期望abc@def并接收'‘。
发布于 2020-07-07 18:50:32
因为您使用的是MUI组件的TextField组件,所以您不能使用getByLabelText获得真正的输入。相反,您应该使用getByPlaceholderText。试试这个:
const setup = () => {
const utils = render(<UnderConstruction />)
const input = utils.getByPlaceholderText('Email')
return {
input,
...utils,
}
}
test('It should set the email input', () => {
const { input } = setup();
const element = input as HTMLInputElement;
fireEvent.change(element, { target: { value: 'abc@def' } });
console.log(element.value);
expect(element.value).toBe('abc@def');
})
发布于 2020-07-09 02:47:20
如果像这样使用UI库,如果getByLabelText或getByPlaceholderText不能工作,我通常会这样获取底层的输入元素:
// add a data-testid="myElement" on the TextField component
// in test:
fireEvent.change(getByTestId('myElement').querySelector('input'), { target: { value: 'abc@def' } });但这并不理想,应该尽可能使用getByLabelText或getByPlaceholderText。
https://stackoverflow.com/questions/62768977
复制相似问题