[英]jest and testing-library controlled input
I'm trying to apply a unit test in my custom input component我正在尝试在我的自定义输入组件中应用单元测试
If I pass the value prop in the <Input />
in the render function, the test fails.如果我在渲染function 的
<Input />
中传递value属性,则测试失败。
Does anyone know the reason?有谁知道原因?
In controlled components like this input, what we can test to have valid unit tests?在像这个输入这样的受控组件中,我们可以测试什么来获得有效的单元测试?
Thanks谢谢
Input.tsx输入.tsx
import React, {ChangeEvent, FunctionComponent} from 'react';
import styles from './Input.module.css'
export interface InputProps {
type?: string
disabled?: boolean
value?: string
onChange?: (value: string) => void
}
const Input: FunctionComponent<InputProps> = ({
type= 'text',
disabled = false,
value,
onChange,
}) => {
const handleOnChange = (e: ChangeEvent<HTMLInputElement>) => {
const value = e.currentTarget.value
if (onChange) {
onChange(value)
}
}
return (
<div className={styles.inputWrapper}>
<input
className={styles.input}
type={type}
disabled={disabled}
value={value}
onChange={handleOnChange}
/>
</div>
);
}
export default Input;
Input.test.tsx输入.test.tsx
// PASS WITHOUT ANY ERRORS
it('should has the new value', async () => {
const user = userEvent.setup()
const onChangeMock = jest.fn();
const { getByRole } = render(<Input onChange={onChangeMock} />)
const input = getByRole('textbox')
expect(input).toHaveValue('')
await user.type(input, 'new input value')
expect(input).toHaveValue('new input value')
})
// FAILS
it('should has the new value', async () => {
const user = userEvent.setup()
const onChangeMock = jest.fn();
const { getByRole } = render(<Input value="" onChange={onChangeMock} />)
const input = getByRole('textbox')
expect(input).toHaveValue('')
await user.type(input, 'new input value')
expect(input).toHaveValue('new input value')
})
You can use rerender
function that is returned from render
.您可以使用从
render
返回的重新rerender
function 。
With this, you send new value into your component, input has a new value and then you can assert for that value in the input.有了这个,您将新值发送到您的组件中,输入有一个新值,然后您可以在输入中为该值断言。
In your case, your test needs to have also checking if onChange
method is called when you do userEvent.type()
or if that does not work you can use fireEvent.change(input...)
.在您的情况下,您的测试还需要检查在您执行
userEvent.type()
时是否调用了onChange
方法,或者如果这不起作用,您可以使用fireEvent.change(input...)
。
it('should has the new value', async () => {
const user = userEvent.setup();
const onChangeMock = jest.fn();
const { getByRole, rerender } = render(<Input value="" onChange={onChangeMock} />);
const input = getByRole('textbox');
expect(input).toHaveValue('');
rerender(<Input value="new input value" onChange={onChangeMock} />);
expect(input).toHaveValue('new input value');
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.