Test Case:
it("Test Email text by test id" , () => {
const testIDName='email-title';
const {getByTestId} = render(
<Provider store={store}>
<NavigationContainer><Login /></NavigationContainer>
</Provider>);
const foundID=getByTestId(testIDName);
expect(foundID).toBeDefined();
})
Element Structure:
<Text testID= {'email-title'} style={styles.emailText}>Email</Text>
Error Being Thrown:
Unable to find an element with testID: email-title
63 | <NavigationContainer><Login /></NavigationContainer>
64 | </Provider>);
> 65 | const foundID=getByTestId(testIDName);
| ^
66 | expect(foundID).toBeDefined();
67 | })
68 |
Libraries utilised :
– testing-library/react-native
I’m new to unit testing react native component, and not sure why element is not recognising the test ID.
Any Help would be appreciated at this point
2
Answers
you need to mock the provider and that navigation:
before the describe do this:
On the TSX file :
I think @Rodrigo Dias has the right approach. I think some additional improvements can be made:
in store.ts:
I’d prefer using toBeVisible over toBeTruthy, because that is more strict. It requires elements to be visible, rather then just exist, which I assume is what you want.
Also, don’t use desctructering for the getByTestId. Instead you can use screen, which automticaly has all the query functions on it for the latest render:
"eslint-plugin-testing-library": "^5.11.0",
that enforces some of these best practices, which I recomend installing.