Home > Software engineering >  getByTestID not working for custom component
getByTestID not working for custom component

Time:01-21

Working on writing a unit test for a large component. I've written one before for a smaller component, but this has several other custom components nested inside. I'm trying to select it so I can then figure out what to do with it, but I can't even get to that point right now.

PriceOverride.tsx

This is a part of what's getting rendered by the component. PriceOverrideDateRange is another custom component, and I'm trying to target it with the testID
       <Counter
          containerMargin={{ marginTop: -5 }}
          defaultCounter={itemCount}
          labelText={t('priceMultiple')}
          onSelectCounter={itemQuantity}
          min={1}
        />
              <PriceOverrideDateRange testID='dateRange' startDate={startDate} endDate={endDate} onSelectDateRange={onChangeDateInterval} />
        <Counter
          containerMargin={{ marginTop: -5 }}
          defaultCounter={labelCount}
          labelText={t('common:labelQuantity')}
          onSelectCounter={labelQuantity}
        />

PriceOverride.test.tsx

This is the part of the test I'm working on
  it('should be able to change the date interval', () =>{


    const navContextValue: any = {
      isFocused: () => false,
      addListener: jest.fn(() => jest.fn())
    };

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

    //Render with the props you want
    const { getByTestId } = render(        
    <Provider store={store}>
      <NavigationContext.Provider value={navContextValue}>
          <PriceOverride navigation={props.navigation}/>
      </NavigationContext.Provider>
    </Provider>, );

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


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


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

  });

And this is the error message I'm getting:

  ● Price Details Test › should be able to change the date interval

    Unable to find an element with testID: dateRange

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

CodePudding user response:

You need to pass the testID to the component as props and then add it the the view you are using I will add a simple example.

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