【发布时间】:2020-10-27 08:09:51
【问题描述】:
不幸的是,我有一个测试揭示了我对如何使用 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>
首先 as cast 是为了让 TypeScript 满意。其次主要是围绕我使用fireEvent来模拟用户输入。关于如何测试此功能的任何想法?现在测试失败了,因为它期待 abc@def 并接收 ''。
【问题讨论】:
标签: reactjs jestjs material-ui react-testing-library