- Dan Dobos
Testing in React Part 1: Jest
Updated: Dec 15, 2020
Why Jest? Jest is a well-documented JavaScript Testing Framework that requires little configuration, can be extended to match your requirements, and is focused on simplicity.
Are you already using another testing library and want to switch... you can try Codemods. Is made for migrating JavaScript and TypeScript test files from AVA, Chai, Expect.js , Jasmine, Mocha, proxyquire, Should.js, and Tape to Jest.
Jest is used by Facebook, Twitter, Instagram, Spotify, and many others. It works with projects using: Babel, TypeScript, Node, React, Angular, Vue, and more!
Let's see what is it all about!
1. Create a new project, add a package.json file and add jest
npm init -y and yarn add --dev jest
2. Create a sum.js file with a simple function and export it
function sum(a, b) { return a + b; } module.exports = sum;
3. Create a sum.test.js file that will contain the tests and import the sum function
const sum = require('./sum');
Jest is searching for a folder named __tests__ or any file that has the spec or test syntax
4. Use the optional describe function to group specific tests
describe('sum function', () => { });
The first parameter is a string that will be displayed in the console and the second parameter is a function that will contain all the desired tests
5. Inside the describe function add the it function
it('expected result', () => { });
The first parameter describes the expected result and the second one is a function, the test that needs to run
6. Inside the it function add the assertion
expect(sum(3, 4)).toEqual(7);
The expect function is used every time you want to test a value and is used with a "matcher" function to assert something about a value. See the expect API documentation or the jest cheat-sheet
7. You are almost there, just need to change the script to invoke jest and run yarn test in the console
"scripts": {"test": "jest --watch *.js"}// in package.json
yarn test //in the console
Because we added watch every time we modify a javascript file, all the tests will run automatically.

Thank you for reading this post! I hope you find at least some of my recommendations useful! For improvements or other article suggestions, you can contact me on Linkedin. You can check out the next chapter Testing in React Part 2: Enzyme