Testing tools for React Apps

Image result for react


In today's blog we will discuss some testing tools of react apps .In general we write code to work, but now a days only writing a code is not enough , it should be less complex and more accurate ,efficient too .

1. ESLINT :- There are so many formats in which java Scripts code is written now a days by different developer so before developing a project coding styles parameters are being set for the react apps .(here react app means , reactjs and react native) .
example -
function add(x, y){
    return x+y ;
}
ES6 syntax -
const add = (x, y) => {
    return x+y
}
Both syntax are correct but setting a parameter is vary important . That's what is done by eslint;
It is also use for the testing of a function :
example -
 // App.js
function add(x, y) {
    return x+y;
}
2. console.log testing :-
test :
console.warn(add(1,2) === 3 , "this is a error function");
console.warn(add(1,6) === 7 , "this is a error function");
console.warn(add(1,21) === 30 , "this is a error function"); // error
you can write as many tests for any function you want .

#installation
npm install eslint

3. Prettier :- This is not literally a testing tool but a formatter . This ensures that your code is in correct format . Eslint only tells that whether or not your code is in correct format of style while prettier corrects the format , as per the standards of esling .
This gives  a fully formatted code . you can fix the fixable issue of eslint with "--fix " command .
And it will do all coding styles for you .

4. Chrome Developer tools :- these are the most important tesing tools . Without them development is seems to be more tough than it actually is . React Developer tools extemsion at chrome is one of chrome developer tools for react . It gives you all break points and components and callback, tracecalls . It provides many features that are helpful in development .

5. JEST :- This is a Integration testing tool . This is used for testing of components after testing of functions and formats and code style .

Testing React Apps With `JEST` (Most important and most widely used)

At Facebook, we use Jest to test React applications.

Setup

Setup : with Create React App

If you are new to React, we recommend using Create React App. It is ready to use and ships with Jest! You will only need to add react-test-renderer for rendering snapshots.
Run
yarn add --dev react-test-renderer

Setup without Create React App

If you have an existing application you'll need to install a few packages to make everything work well together. We are using the babel-jest package and the react babel preset to transform our code inside of the test environment. Also see using babel.
Run
yarn add --dev jest babel-jest @babel/preset-env @babel/preset-react react-test-renderer
Your package.json should look something like this (where <current-version> is the actual latest version number for the package). Please add the scripts and jest configuration entries:
// package.json
  "dependencies": {
    "react": "<current-version>",
    "react-dom": "<current-version>"
  },
  "devDependencies": {
    "@babel/preset-env": "<current-version>",
    "@babel/preset-react": "<current-version>",
    "babel-jest": "<current-version>",
    "jest": "<current-version>",
    "react-test-renderer": "<current-version>"
  },
  "scripts": {
    "test": "jest"
  }
// babel.config.js
module.exports = {
  presets: ['@babel/preset-env', '@babel/preset-react'],
};
And you're good to go!

Snapshot Testing

Let's create a snapshot test for a Link component that renders hyperlinks:
// Link.react.js
import React from 'react';

const STATUS = {
  HOVERED: 'hovered',
  NORMAL: 'normal',
};

export default class Link extends React.Component {
  constructor(props) {
    super(props);

    this._onMouseEnter = this._onMouseEnter.bind(this);
    this._onMouseLeave = this._onMouseLeave.bind(this);

    this.state = {
      class: STATUS.NORMAL,
    };
  }

  _onMouseEnter() {
    this.setState({class: STATUS.HOVERED});
  }

  _onMouseLeave() {
    this.setState({class: STATUS.NORMAL});
  }

  render() {
    return (
      <a
        className={this.state.class}
        href={this.props.page || '#'}
        onMouseEnter={this._onMouseEnter}
        onMouseLeave={this._onMouseLeave}
      >
        {this.props.children}
      </a>
    );
  }
}
Now let's use React's test renderer and Jest's snapshot feature to interact with the component and capture the rendered output and create a snapshot file:
// Link.react.test.js
import React from 'react';
import Link from '../Link.react';
import renderer from 'react-test-renderer';

test('Link changes the class when hovered', () => {
  const component = renderer.create(
    <Link page="http://www.facebook.com">Facebook</Link>,
  );
  let tree = component.toJSON();
  expect(tree).toMatchSnapshot();

  // manually trigger the callback
  tree.props.onMouseEnter();
  // re-rendering
  tree = component.toJSON();
  expect(tree).toMatchSnapshot();

  // manually trigger the callback
  tree.props.onMouseLeave();
  // re-rendering
  tree = component.toJSON();
  expect(tree).toMatchSnapshot();
});
When you run yarn test or jest, this will produce an output file like this:
The next time you run the tests, the rendered output will be compared to the previously created snapshot. The snapshot should be committed along code changes. When a snapshot test fails, you need to inspect whether it is an intended or unintended change. If the change is expected you can invoke Jest with jest -u to overwrite the existing snapshot.
The code for this example is available at examples/snapshot.

Snapshot Testing with Mocks, Enzyme and React 16

There's a caveat around snapshot testing when using Enzyme and React 16+. If you mock out a module using the following style:
jest.mock('../SomeDirectory/SomeComponent', () => 'SomeComponent');
Then you will see warnings in the console:
Warning: <SomeComponent /> is using uppercase HTML. Always use lowercase HTML tags in React.

# Or:
Warning: The tag <SomeComponent> is unrecognized in this browser. If you meant to render a React component, start its name with an uppercase letter.

DOM Testing

If you'd like to assert, and manipulate your rendered components you can use react-testing-libraryEnzyme, or React's TestUtils. The following two examples use react-testing-library and Enzyme.

react-testing-library

You have to run yarn add --dev @testing-library/react to use react-testing-library.
Let's implement a checkbox which swaps between two labels:
// CheckboxWithLabel.js

import React from 'react';

export default class CheckboxWithLabel extends React.Component {
  constructor(props) {
    super(props);
    this.state = {isChecked: false};

    // bind manually because React class components don't auto-bind
    // http://facebook.github.io/react/blog/2015/01/27/react-v0.13.0-beta-1.html#autobinding
    this.onChange = this.onChange.bind(this);
  }

  onChange() {
    this.setState({isChecked: !this.state.isChecked});
  }

  render() {
    return (
      <label>
        <input
          type="checkbox"
          checked={this.state.isChecked}
          onChange={this.onChange}
        />
        {this.state.isChecked ? this.props.labelOn : this.props.labelOff}
      </label>
    );
  }
}
// __tests__/CheckboxWithLabel-test.js
import React from 'react';
import {cleanup, fireEvent, render} from '@testing-library/react';
import CheckboxWithLabel from '../CheckboxWithLabel';

// automatically unmount and cleanup DOM after the test is finished.
afterEach(cleanup);

it('CheckboxWithLabel changes the text after click', () => {
  const {queryByLabelText, getByLabelText} = render(
    <CheckboxWithLabel labelOn="On" labelOff="Off" />,
  );

  expect(queryByLabelText(/off/i)).toBeTruthy();

  fireEvent.click(getByLabelText(/off/i));

  expect(queryByLabelText(/on/i)).toBeTruthy();
});
The code for this example is available at examples/react-testing-library.

Enzyme

You have to run yarn add --dev enzyme to use Enzyme. If you are using a React version below 15.5.0, you will also need to install react-addons-test-utils.
Let's rewrite the test from above using Enzyme instead of react-testing-library. We use Enzyme's shallow renderer in this example.
// __tests__/CheckboxWithLabel-test.js

import React from 'react';
import {shallow} from 'enzyme';
import CheckboxWithLabel from '../CheckboxWithLabel';

test('CheckboxWithLabel changes the text after click', () => {
  // Render a checkbox with label in the document
  const checkbox = shallow(<CheckboxWithLabel labelOn="On" labelOff="Off" />);

  expect(checkbox.text()).toEqual('Off');

  checkbox.find('input').simulate('change');

  expect(checkbox.text()).toEqual('On');
});
The code for this example is available at examples/enzyme.

Don't forget to install the @babel/core and babel-preset-jest packages for this example to work.
To make this work with Jest you need to update your Jest configuration with this: "transform": {"\\.js$": "path/to/custom-transformer.js"}.
If you'd like to build a transformer with babel support, you can also use babel-jest to compose one and pass in your custom configuration options:
The above examples are of unit and Integration testing ,But what if we need a  "End to End" testing . Unfortunately there is not any specific way for end to end testing . We have to test the app manually for end to end testing . 
6.Detox :- But the WIX has been developing " Detox " for end to end testing of react apps . it performs a serial of actions as the noraml user perform from installation to uninstallation . 
These all testings are done in development mode not in production mode . So be sure to be in development mode for performing Detox end to end testing . 

7. Mocha :-Mocha is a JavaScript test framework for Node.js programs, featuring browser support, asynchronous testing, test coverage reports, and use of any assertion library. It is very configurable and gives the developer full control over how they wish to test their code, with which tools, while you can plug in and out most supporting libraries and tools in your chain.
Just like Jest and other frameworks, when used it React, Mocha can be combined with Enzyme, and also with Chai and other libraries for assertion, mocking etc. Some prefer it to test their React apps as well, often when in need of specific advanced configurations with a mature and rich toolset. Yet, this also can become a pain, as common tasks (like snapshots) will require adding more tools and further configurations in your workflow.

8. React-testing-library:-
For those of you who don’t use Enzyme, like Facebook itself, the React team recommends using the react-testing-library to simulate user behavior in your tests. Much like Enzyme, this library is a simple and complete set of React DOM testing utilities aimed to imitate actual user actions and workflows. Choosing between react-testing-library an Enzyme? Perhaps this will help.

9 .  Enzyme :-  It’s hard to dive into React testing, and particularly with testing frameworks like Jest, without crossing paths with Enzyme by AirbnbEngEnzyme isn’t a testing framework, but rather a testing utility for React that makes it easier to test the outputs of components, abstracting the rendering of components.
Much like JQuery used to do on the DOM, Enzyme lets you manipulate, traverse, and in some ways simulate runtime given the output. In short, it can really help you render components, find elements and interact with them. Try using Jest and Enzyme together, or check out Enzyme with Karma, Mocha etc.

10 .React test utils and test renderer :-True, this isn’t a library but rather a collection of useful utilities (like act(), mockComponent(), isElement and more) in React that help to test components using a testing framework of your choice. Test renderer lets you render React components into pure JavaScript objects without depending on the DOM.
Knowledge of these useful tools is key in successfully testing your components and apps in React, and without having to force external tools into doing more than they should. Your decision-tree journey should probably start here.


-- Sundaram Dubey






Comments

Unknown said…
Strange "water hack" burns 2 lbs in your sleep

Over 160 000 men and women are hacking their diet with a easy and secret "water hack" to drop 2lbs every night while they sleep.

It's easy and it works every time.

Here's how to do it yourself:

1) Go get a drinking glass and fill it with water half the way

2) Then learn this crazy hack

and you'll become 2lbs skinnier as soon as tomorrow!
jersseyjohn said…


Devopes training in Hyderabad RS Trainings is a One of the best quality training center for online, Classroom and Corporate trainings In Hyderabad . DevOps is the mix of programming of programming improvement and programming tasks. It joins the method of improvement and activities. They go near to close or are done at same time.

Popular posts from this blog

Amazon Web Services

Google Code-In mentorship experience :)

Hacker Rank all java and python problem solutions