我正在努力理解如何在使用cypress- react -unit-test的同时更新react组件的道具。
这里我有一个简单的受控输入组件。
interface MyInputProps {
inputVal: string
onInputChanged(val: string): void
}
export const MyInput = ({ inputVal, onInputChanged }: MyInputProps) => {
return <input
type='text'
value={inputVal}
onChange={e => onInputChanged(e.target.value)}
/>
}然后,我想通过给组件一个初始值''来测试该组件,然后执行类似cy.get('input').type('a')的操作。然后,我期望调用onInputChanged回调函数。
但这就是我被卡住的地方。如何处理更新后的值('a')?我不能在测试中使用钩子或状态,那么如何让我的组件使用更新后的值重新呈现呢?先做mount(<MyInput inputVal='' />),然后做mount(<MyInput inputVal='a' />)似乎是错误的,因为我正在挂载一个不同的组件,并且我没有测试该组件对属性更新的反应。
// MyInput.spec.tsx
describe('My Input', () => {
it('updates when props change', () => {
mount(<MyInput
inputVal=''
onInputChanged={(newVal) => {
/* What do I do here? How do I update the props */
return null
}}
/>);
/* Update props */
/* Re-render somehow */
})
})发布于 2020-09-23 15:06:24
我认为问题不在于您的测试,而在于您的MyInput组件。
将状态设置为MyInput或使用defaultValue代替value
export const MyInput = ({ inputVal, onInputChanged }: MyInputProps) => {
return (
<input
type="text"
defaultValue={inputVal}
onChange={(e) => onInputChanged(e.target.value)}
/>
);
};正如你所知道的,设置value={inputVal}将使输入永远不变,只有当你改变inputVal时才会改变。
https://stackoverflow.com/questions/63910218
复制相似问题