a blog for those who code

Tuesday, 3 September 2019

Writing Unit Tests for React Component using Jest and Enzyme

In this post we will look into what I have learned writing unit tests for React Component using Jest and Enzyme. Writing unit tests is considered as wastage of time by most of the developers, but the truth is it will make you write better code with less bugs. Recently we have moved from jQuery to React and thus we started writing our unit tests in Jest with Enzyme.


Initially our goal was to have a code coverage of around 75-80%, but we were so hooked to write test cases we achieved 92.78% of code coverage. Isn't it amazing !!!.



Jest is a test runner which run our tests in parallel whereas Enzyme is a JavaScript testing tool which helps us to traverse, manipulate our react component. The things I have learned are as follows :


1. Your .babelrc file should have required presets and plugins :

{
    "presets": ["@babel/react", "@babel/preset-env"],
    "plugins": [
        "transform-object-rest-spread",
        "transform-react-jsx",
        "@babel/plugin-proposal-class-properties"
    ]
}


2. You package.json should mock CSS modules and also specify from where to collect coverage from

"jest": {
  "moduleNameMapper": {
    "\\.(css|less)$": "identity-obj-proxy"
  },
  "collectCoverageFrom": [
    "src/**/*.js",
    "!**/node_modules/**",
    "!**/vendor/**"
  ]
}


3. You should know the difference between shallow and mount in enzyme before starting to write test cases. Shallow rederes only the single component whereas mount renders the full DOM including the child components. I mainly use Shallow as much as possible but when I have to do some processing with the child component I use mount.

4. If you use axios, then you should mock the resolved values as shown below :

jest.mock('axios');

test("should fetch dropdown values", async () => {
    const resp = {data: dropdownValues};
    axios.get.mockResolvedValue(resp);
    const wrapper = shallow(<MyComponent />);
    expect(wrapper.exists()).toBe(true);

});

5. You can do any operations on wrapper like click, keydown, mouseenter using simulate function.

No comments:

Post a comment