Non-visible modal content shows up in queries
Describe the bug
Hi, thanks for taking a look at this! I'm fairly new to react-native, but have a lot of experience with web testing-library variants and ran across some unexpected (to me) behavior. Query methods find nodes in non-visible modals.
I think this is what this user was getting at https://github.com/callstack/react-native-testing-library/issues/508
Steps to Reproduce
Here's a simple example test I set up to test this out
// App.js
import React from "react";
import { Modal, Text, View } from "react-native";
const App = () => {
return (
<View>
<Modal visible={false}>
<View>
<Text>Exciting content</Text>
</View>
</Modal>
</View>
);
};
export default App;
// App.test.js
import React from "react";
import { render, fireEvent } from "@testing-library/react-native";
import App from "./App";
it("shows the modal on button click", () => {
const { queryByText } = render(<App />);
expect(queryByText("Exciting content")).toBeNull(); // fails
});
Expected behavior
I'd expect this test to pass, since there's no modal content visible to the user while the modal is not visible.
If this is expected behavior, is there a recommended way to test appearance/disappearance modals?
Versions
@testing-library/[email protected]
@cfradella If you need to match a hidden element (your modal considered hidden as it has importantForAccessiblity="no-hide-descendents" prop), you need to pass includeHiddenElements: true option to your query:
screen.getByTestId("particleAnimation", { includeHiddenElements: true })
Docs link: https://callstack.github.io/react-native-testing-library/docs/api-queries#includehiddenelements-option
Note: the solution you mentioned above is stale and referred to pre v12 versions of RNTL.
Additionally, we no longer recommend using toBeTruthy() to check for elements existance. The recommended version would be:
expect(screen.getByTestId("particleAnimation", { includeHiddenElements: true })).toBeOnTheScreen()
@cfradella If you need to match a hidden element (your modal considered hidden as it has
importantForAccessiblity="no-hide-descendents"prop), you need to passincludeHiddenElements: trueoption to your query:screen.getByTestId("particleAnimation", { includeHiddenElements: true })Docs link: https://callstack.github.io/react-native-testing-library/docs/api-queries#includehiddenelements-option
Note: the solution you mentioned above is stale and referred to pre v12 versions of RNTL.
Additionally, we no longer recommend using
toBeTruthy()to check for elements existance. The recommended version would be:expect(screen.getByTestId("particleAnimation", { includeHiddenElements: true })).toBeOnTheScreen()
That worked, thanks for saving my day. : 👍