Test Case using Enzyme: React Component

Assuming you have reactjs application configured,we are going to define component in react js and will test it using enzyme.

Gorakh Nath
2 min readApr 7, 2019

Add a file App.js now add a sample dom element in the render function, for each element we will define an Id:-s

added sample element in render function

Now we have to test that the element is render in dom or not.To test this we will have to add install the following package:-

Now add the test file App.test.js and add following code:-

import React from “react”;

import each from “jest-each”;

import App from “./App”;

import Adapter from “enzyme-adapter-react-16”;

import { configure, shallow, mount } from “enzyme”;

configure({ adapter: new Adapter() });

describe(“Confirm element visibility”, () => {

let wrapper;

beforeEach(() => {

wrapper = mount(shallow(<App />).get(0));

});

afterEach(() => {

wrapper.unmount();

});

each([

“#dvApp”,

“#header”,

“#logo”,

“#title”,

“#dvForm”,

“#form”,

“#dvEmpId”,

“#lbEmpName”,

“#txtEmpName”,

“#dvFromSubmit”,

“#btnSubmit”

]).test(“Ensure that %s field is rendered by default”, selector => {

var match = wrapper.find(selector).hostNodes().length === 1;

expect(match).toEqual(true);

});

});

In above example we are testing the count of element in dom, according to our code the length of element should be one.

Wrap up:

run the command : npm test App.test

All test case should pass and output should come as:-

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Gorakh Nath
Gorakh Nath

No responses yet

Write a response