Set up react-native-testing-library [Part 1/3]
Testing ⋉ Quality
Introduction
Today every organization is setting up the standards for bringing up the quality in code. They set a threshold for different pillars of programming like testing, static code quality, etc. In this blog, I will mention all the steps/configurations which is required to quickly start writing unit test cases. It will help you to set up @testing-library/react-native for your fresh/boilerplate or already developed react native project.
Target Audience
If you have started developing or already developed an application in react-native and would like to write unit test cases this blog would be of great use.
What is so special about this blog?
It took several hours to set up a workable, exception-free unit testing environment for my project. After reading several blogs, official documents, Github discussion threads, and obviously StackOverflow I found some configurations which could save you several hours:).
Assumptions
I am assuming you already have a react-native project (boilerplate or pre-developed) on your machine, if not please take a pause and set up a project first.
Let’s get started now
- Install the package using the below command in terminal
npm i @testing-library/react-native
2. If you have an entry related to jest in package.json (as shown in the below code snippet) remove it we will keep all jest related configs in one place
jest: {
preset: 'react-native'
}
3. Create jest.config.js file at the root location of your project
module.exports = {
preset: 'react-native',
testEnvironment: 'jsdom',
transformIgnorePatterns: [
'node_modules/(?!(@react-native|react-native|@react-native- community|rect-native-vector-icons|react-native-iphone-x-helper|react-native-swipe-gestures))'
]
}
preset: It should point to the node module which has jest.preset file
testEnvironment: If any library uses animation then it should be ‘jsdom’. This key has ‘node’ as the default value.
transformIgnorePatterns: Modules that are not transpiled should be mentioned in the transformIgnorePatterns array
Potential Error’s Resolution
Whatever configurations we have made so far are sufficient to run unit test cases whether it is covering the business or rendering logic. It totally depends on which modules you are using in the project, as we have all required jest configuration in place you just need to tweak them according to project setup.
If you are getting the below error you just need to add the relevant module to transformIgnorePattern
Jest encountered an unexpected token
This usually means that you are trying to import a file which Jest cannot parse, e.g. it’s not plain JavaScript.
By default, if Jest sees a Babel config, it will use that to transform your files, ignoring “node_modules”.