【发布时间】:2022-01-24 18:48:29
【问题描述】:
我正在为我正在单元测试的功能编写测试用例。我想编辑嵌入在多个自定义组件中的文本字段,但我不知道如何访问它:
TestFile.test.tsx
it('should be able to change quantity', () =>{
//Mock out dependent function with jest
//Nothing here right now
//Render with the props you want
render(
<MainComponent /> );
//Locate screen components for test
const counter = screen.queryByTestId("counter");
//Perform user actions
fireEvent.change(counter, 4); <--This is the line where I'm trying to access what I want
//Measure against expect cases
expect(counter).toBe(4);
});
MainComponent.tsx
这是我试图访问的组件。问题是,`fireEvent.change` 不起作用,因为它是一个自定义组件。至少,我认为这就是它不起作用的原因。<Counter
data-testid='counter' <--data-testid is here right now
containerMargin={{ marginTop: -5 }}
/>
Counter.tsx
`Counter` 内部是另一个自定义组件,`TextField`<TextField
{...props}
/>
TextField.tsx
在 TextField 内部是我要访问的文本输入:<TextInput
{...props}
/>
错误信息
当我尝试运行测试时,我收到此错误: ● Test › should be able to change quantity
Unable to fire a "change" event - please provide a DOM element.
189 |
190 | //Perform user actions
> 191 | fireEvent.change(counter, 4);
| ^
192 |
193 | //Measure against expect cases
194 | expect(counter).toBe(4);
我不能将data-testid 属性放入TextField 或TextInput 本身,因为在我正在测试的页面的呈现中还有另一个Counter。任何建议或故障排除都会有所帮助,谢谢!
【问题讨论】:
-
我建议用react-testing-library替换html标签
标签: reactjs typescript react-native unit-testing react-testing-library