score:177
toBeInTheDocument
is not part of RTL. You need to install jest-dom to enable it.
And then import it in your test files by:
import '@testing-library/jest-dom'
score:-5
Instead of doing:
expect(queryByText('test')).toBeInTheDocument()
you can find and test that it is in the document with just one line by using
let element = getByText('test');
The test will fail if the element isn't found with the getBy call.
score:0
install required packages
npm install --save-dev @testing-library/jest-dom eslint-plugin-jest-dom
create
jest-setup.js
in the root folder of your project and addimport '@testing-library/jest-dom'
in
jest.config.js
setupFilesAfterEnv: ['/jest-setup.js']
TypeScript
only, add the following to thetsconfig.json
file. Also, change .js extension to .ts."include": ["./jest-setup.ts"]
toBeInTheDocument()
and many similar functions are not part of the React-testing-library
. It requires installing an additional package.
score:1
None of the answers worked for me because I made the silly mistake of typing toBeInDocument()
instead of toBeInTheDocument()
. Maybe someone else did the same mistake :)
score:2
I had a hard time solving that problem so I believe it's important to note the followings if you're using CREATE REACT APP for your project:
- You DO NOT need a
jest.config.js
file to solve this, so if you have that you can delete it. - You DO NOT need to change anything in
package.json
. - You HAVE TO name your jest setup file
setupTests.js
and have it under thesrc
folder. It WILL NOT work if your setup file is calledjest.setup.js
orjest-setup.js
.
score:6
Some of the accepted answers were basically right but some may be slightly outdated: Some references that are good for now:
Here are the full things you need:
- in the project's
<rootDir>
(aka wherepackage.json
andjest.config.js
are), make sure you have a file calledjest.config.js
so that Jest can automatically pick it up for configuration. The file is in JS but is structured similarly to a package.json. - Make sure you input the following:
module.exports = {
testPathIgnorePatterns: ['<rootDir>/node_modules', '<rootDir>/dist'], // might want?
moduleNameMapper: {
'@components(.*)': '<rootDir>/src/components$1' // might want?
},
moduleDirectories: ['<rootDir>/node_modules', '<rootDir>/src'],
setupFilesAfterEnv: ['<rootDir>/src/jest-setup.ts'] // this is the KEY
// note it should be in the top level of the exported object.
};
Also, note that if you're using typescript you will need to make sure your
jest-setup.ts
file is compiled (so add it tosrc
or to the list of items to compile in yourtsconfig.json
.At the top of
jest-setup.ts/js
(or whatever you want to name this entrypoint) file: addimport '@testing-library/jest-dom';
.You may also want to make sure it actually runs so put a
console.log('hello, world!');
. You also have the opportunity to add any global functions you'd like to have available in jest such as (global.fetch = jest.fn()
).Now you actually have to install
@testing-library/jest-dom
:npm i -D @testing-library/jest-dom
in the console.
With those steps you should be ready to use jest-dom:
Without TS: you still need:
npm i -D @testing-library/jest-dom
- Creating a
jest.config.js
and adding to it a minimum of:module.exports = { setupFilesAfterEnv: ['<rootDir>/[path-to-file]/jest-setup.js'] }
. - Creating a
[path-to-file]/jest-setup.js
and adding to it:import '@testing-library/jest-dom';
.
The jest-setup file is also a great place to configure tests like creating a special renderWithProvider(
function or setting up global window functions.
score:6
Having tried all of the advice in this post and it still not working for me, I'd like to offer an alternative solution:
Install jest-dom:
npm i --save-dev @testing-library/jest-dom
Then create a setupTests.js
file in the src directory (this bit is important! I had it in the root dir and this did not work...). In here, put:
import '@testing-library/jest-dom'
(or require(...)
if that's your preference).
This worked for me :)
score:11
When you do npm i @testing-library/react
make sure there is a setupTests.js file with the following statement in it
import '@testing-library/jest-dom/extend-expect';
score:103
As mentioned by Giorgio, you need to install jest-dom. Here is what worked for me:
(I was using typescript)
npm i --save-dev @testing-library/jest-dom
Then add an import to your setupTests.ts
import '@testing-library/jest-dom/extend-expect';
Then in your jest.config.js you can load it via:
"setupFilesAfterEnv": [
"<rootDir>/src/setupTests.ts"
]
Source: stackoverflow.com
Related Query
- React testing library - TypeError: expect(...).toHaveTextContent is not a function
- Dispatch is not a function - React Testing Library with React Redux Hooks
- React Testing Library - TypeError: actImplementation is not a function
- Expect is not a function in react testing library
- Why does the jest mock function not getting executed in my test with react testing library?
- Mock function not being called using jest and testing library on react app
- React Testing Library Mock function not called
- router.prefetch is not a function , Unable to check submit function in react testing library
- Testing <Input/> component from Material UI using Testing React Library and the call back function is not recongnized in the onChange prop
- React - useState - why setTimeout function does not have latest state value?
- TypeError: environment.setup is not a function in React Testing
- fireEvent.keyDown not working as expected on my Jest + React Testing Library test
- Why is my React component library not tree-shakable?
- Property 'value' does not exist on type 'HTMLElement' in React Testing Library
- _this.store.getState is not a function when testing react component with enzyme and mocha
- React Testing Library does not find elements using getAllByTestId after initial render
- React testing library not rendering Emotion CSS
- React Testing - TypeError: localStorage.getItem is not a function
- React testing library fireEvent.click not working
- In React why does calling a function from another function in our code not work and display?
- Why does react call render function if I have not changed the reference of the state?
- Why react calls function in subcomponents event when this subsomponents not rendered?
- React Testing Library Invariant failed: You should not use <Route> outside a <Router>
- "TypeError: react.useContext is not a function" when mocking context Providers with React Testing Library
- Attempts to check for element not existing with React Testing Library always failing
- React hooks not returning updated state values inside callback function from library events (FabricJS)
- React Testing Library - Mock Service Worker response not used by component
- React jest testing Google Maps Api , Uncaught TypeError: this.autocomplete.addListener is not a function
- React testing library Router tests not passing when following RTL's own guide
- How to test a function inside React functional component using jest.spyOn with React Testing Library
More Query from same tag
- Type '{}' is missing the following properties from type - TS error
- Render Full Calendar of DatePicker on a page
- Replace Parent component with Child component
- Ant Design: How can I handle Button in Card extra onClick event?
- Tailwind (v.2) Flex Width Not Growing or Shrinking
- Why do I see stale data even after invalidating my queries?
- How can I change the value of a context without it resetting after a page change in Ionic React?
- NextJS - ReferrenceError: document is not defined
- Can I use react-select in react-native?
- How to Loop an Array Using Map Function Based on Condition and Then setState?
- How to use react-s3-uploader with reactjs?
- optional chaining operator jest testing
- How can I add to props and make a select option disabled?
- How do I get the range offsets of an entire div in Javascript?
- Unable to retrieve data from Multiple collection firebase
- Form input not changing when using react-testing-library on redux-form
- Fill <object> svg using jss
- How to use the cookie from an http response
- React-Router: Apply logic to component before navigating to a different route
- What is best way to do lazy loading in a Next js Application?
- Trouble sending a response string from my Express server to React front-end
- ReactJS Fetch User Data from API and add to table
- react-highcarts using es6 getting some errors
- Render Picker Items from React-Native picker to populate drop-menu selections
- how to restrict user to enter only 10 characters in mobile field
- How to add add key to react-select multi?
- How to count how many instances of a React component are mounted?
- How to include state/props in useEffect without it becoming a trigger?
- CORS error - Error: Cross origin http://localhost forbidden - in ReactJS/Jest test only
- Using Object.keys(), map(), ...Array(), reduce() and concat() in a single const