Why can't I query react-native-paper elements in my unit tests?
Ask your Question
When writing the unit tests for my react-native app, react-native-paper elements do not render with my components in my tests.
No queries work, and when I print out the jsx of the component with screen.debug() none of the elements are there.
When I updated my import to now use the regular react-native button import { Button } from "react-native";, the expected elements appeared in my test.
Here is the unit test
it("renders correctly and toggles modal", async () => {
const { getByText } = render(
<IDContext.Provider value={{ ID: "mockedID" }}>
<TaskContext.Provider value={{ tasks: [], setTasks: jest.fn() }}>
<ModalToggleButton />
</TaskContext.Provider>
</IDContext.Provider>
);
// Check if the "Show Tasks" button is initially present
const showTasksButton = getByText("Show Tasks");
// getByTestId("showTasks") returns null as well
console.log(showTasksButton)
expect(showTasksButton).toBeTruthy();
// Click the "Show Tasks" button to toggle the modal
fireEvent.press(showTasksButton);
});
This test does not pass when I use the Button imported from react-native-paper like so:
// VERSION THAT IS NOT WORKING using react-native-paper
import React, { useContext, useState } from "react";
import { View, Text } from "react-native";
import { Button } from "react-native-paper";
import ToDoList from "./ToDoList";
import {IDContext} from "../../context/IDContext";
export default function ModalToggleButton() {
const [showModal, setShowModal] = useState(false);
const { ID } = useContext(IDContext) || {}; // Use default empty object to avoid destructuring undefined
return (
<View>
{showModal ? (
<ToDoList ID={ID} showToggleButton={()=> setShowModal(false)}/>
) : (
<Text><Button onPress={() => setShowModal(true)} testID="showTasks">Show Tasks</Button></Text>
)}
</View>
);
}
But when I update the component to this, the test passes and the Button can be interacted with in the test
//WORKING VERSION without react-native-paper
import React, { useContext, useState } from "react";
import { Button, View } from "react-native";
import ToDoList from "./ToDoList";
import {IDContext} from "../../context/IDContext";
export default function ModalToggleButton() {
const [showModal, setShowModal] = useState(false);
const { ID } = useContext(IDContext) || {}; // Use default empty object to avoid destructuring undefined
return (
<View>
{showModal ? (
<ToDoList ID={ID} showToggleButton={()=> setShowModal(false)}/>
) : (
<Button onPress={() => setShowModal(true)} title="Show Tasks"/>
)}
</View>
);
}
This issue is not isolated to react-native-paper Buttons. In fact, any react-native-paper element cannot be found in my unit test, such as TextInputs, but react-native's TextInput is rendered in the tests with no issue.