【问题标题】:getByTestID not working for custom componentgetByTestID 不适用于自定义组件
【发布时间】:2022-01-26 00:30:38
【问题描述】:

正在为大型组件编写单元测试。我之前为一个较小的组件编写了一个,但是其中嵌套了其他几个自定义组件。我正在尝试选择它,这样我就可以弄清楚如何处理它,但我现在什至无法达到这一点。

MainComponent.tsx

这是组件渲染的一部分。 PriceOverrideDateRange 是另一个自定义组件,我正在尝试使用 testID 来定位它
       <Counter
        />
              <MainComponentRange testID='range' />
        <Counter
        />

MainComponent.test.tsx

这是我正在做的测试的一部分
  it('should be able to change the ranfe', () =>{



    //Mock out dependent function with jest
    //Nothing here right now...

    //Render with the props you want
    const { getByTestId } = render(        
          <MainComponent />

);

    //Locate screen components for test
    const range = getByTestId('range');


    //Perform user actions
    fireEvent.changeText(range, "01/22/2022");


    //Measure against expect cases
    expect(dateRange).toBe("1/22/2022");

  });

这是我收到的错误消息:

  ● Main Component Test › should be able to change the range

    Unable to find an element with testID: dateRange

      143 |
      144 |     //Locate screen components for test
    > 145 |     const dateRange = getByTestId('range');
          |                       ^
      146 |
      147 |

【问题讨论】:

    标签: javascript typescript react-native unit-testing jestjs


    【解决方案1】:

    您需要将 testID 作为 props 传递给组件,然后将其添加到您正在使用的视图中,我将添加一个简单的示例。

    const App = () => {
      return <PriceOverrideDateRange testID="dateRange" />
    }
    
    const PriceOverrideDateRange = ({testID}) => {
      return <View testID="dateRange" ><Text>Hello</Text></View>
    } 
    

    【讨论】:

    • 非常感谢!我不知道互动是如何进行的
    猜你喜欢
    • 1970-01-01
    • 2020-09-30
    • 1970-01-01
    • 2018-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-02
    • 2011-12-08
    相关资源
    最近更新 更多