React testing with Jest.

Jest is an open source JavaScript testing framework made by Facebook for React testing. Jest is built on top of Jasmine. Jasmine is a testing framework for JavaScript that is built on the principles of behaviour-driven development. Jasmine does not require any other JavaScript frameworks or even a DOM(Document Object Model). Jest is basically Jasmine on steroids. Some cool features of Jest include that it runs tests in parallel (making them faster), tests asynchronous code using inbuilt timer functions and automatically finds tests and can also be run from the command line. Jest’s coolest feature though, is the fact that it auto-mocks(eg tests everything) by default. You have to specify what not to test, instead of what to test.

React testing with Jest can be done in only a few steps. To install Jest, type npm install --save-dev jest-cli in the command line. After installing, create a directory inside your app called __tests__. This directory will contain all your tests.Then, create a Jest test. Define what Jest should not mock and then setup the test. Run Jest from the command line to start your testing. Run Jest by typingnpm test

An example of a Jest.

//Tells what not to mock

//The mock starts here. The mock is named.
describe('sum', function() {
//Describes what the Mock does.
it('finds the sum of two numbers', function() {
//What is required for the mock to work
var sum = require('../sum.js');
//What the mock will do and what it is expected to match
expect(sum(1, 2)).toBe(3);

Leave a Reply

Your email address will not be published.