How to setup jest test case in NextJS

Cover Image for How to setup jest test case in NextJS
Ullas Kishan
Ullas Kishan
4 min read

Introduction

The developers are used to writing test cases for their components, that is for the validation of the components to ensure the behavior. These test cases will be prior test cases rather than the actual test cases.

We are clear about what is the need for unit test cases. So next we can discuss how to implement and run the unit test cases in your software program.

Here I am particularly going to explain the unit test cases for ReactJS applications and supporting unit test case library.

The widely used testing framework is Jest and it is very easy to handle the test cases. Jest is completing the process with help of other libraries like enzyme for rendering the components.

  • Please follow the below steps to set up the Jest framework in your ReactJS application.

  • Please add the below packages to your applications

create/add a step "test" for running the test cases in package.json on script section along with other commands

 "scripts": {
    "dev": "next",
    "build": "next build",
    "start": "next start",
    "test": "jest" ---> for running the test cases
  },

Now, the initial step is done. there for we can start to create the test files. basically the test files should create the name with [filename].test.js

see the below coding snippet this is how our test file look like.

import React from "react";
import { ContactForm } from "./index"; -- ContactForm is accepting the personal details.
import { shallow } from "enzyme";

describe("enter you contact details", () => {
  const element = shallow(<VCardForm />);
  it("should be able to find first name textbox", () => {
    const renderComponent = element.find("input");
    expect(renderComponent.at(0).props().name).toBe("firstName");
  });
});

Now, Run the test script from terminal by entering npm run test

But unfortunetly we caught an error similar to the below error statement

Enzyme Internal Error: Enzyme expects an adapter to be configured, but found none. To configure an adapter, you should call `Enzyme.configure({ adapter: new Adapter() })` before using any of Enzyme's top level APIs, where `Adapter` is the adapter corresponding to the library currently being tested.

For example:

import Adapter from 'enzyme-adapter-react-15'; To find out more about this, see https://airbnb.io/enzyme/docs/installation/index.html

So, How to fix: Enzyme expects an adapter to be configured and what does it meant ?

The adapter abstracts away anything that changes based on the React version so the core enzyme code can stay the same. This is the need of Enzyme adapter.

To fix the error can be done in few lines of code and need a adapter package based on your React version.

For this example, I have installed npm i @wojtekmaj/enzyme-adapter-react-17

then create a file setupTests.js in the root of the application.

import * as enzyme from "enzyme";
import * as Adapter from "@wojtekmaj/enzyme-adapter-react-17";

enzyme.configure({ adapter: new Adapter.default() });

To make this adapter configuration to work add the file reference to the jest.config.js

So create jest.config.js file to add certain configuration for the unit test cases.

const config = {
  setupFilesAfterEnv: ["<rootDir>/setupTests.js"],
  transform: {
    "^.+\\.(js|jsx|ts|tsx)$": ["babel-jest", { presets: ["next/babel"] }],
  },
};

module.exports = config;

presets: ["next/babel"] this is preset plugin for NextJS application, this can be declared either in .babelrc file or within the configuration file. This is only the major part for NextJS and rest everything similar as normal React applications.

Now we are good to run the test cases against to our testcases.


PASS  src/components/ContactForm.test.js
enter you contact details
  √ should be able to find first name textbox (53 ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        4.408 s
Ran all test suites.

Thank you, I hope this instruction is helps to set up the unit test case for your NextJS application.

More Stories

Access to fetch domain-ABC from origin domain-XYZ blocked by cors policy
Access to fetch domain-ABC from origin domain-XYZ blocked by cors policy

Cross-Origin Resource Sharing (CORS) is a security feature that lets a web page from one domain request resources from a different domain

Ullas Kishan
3 min read
Why SVG element is not reading by NVDA screen reader
Why SVG element is not reading by NVDA screen reader

SVG elements will not add the accessibility atttributes by default, so that will fail to describe by itself, and the NVDA and other screen reader required these attributes to work.

Ullas Kishan
2 min read
A Guide to Resolving Git Conflicts in Your Local Setup
A Guide to Resolving Git Conflicts in Your Local Setup

Despite being acquainted with git, many developers struggle to resolve these conflicts due to a lack of understanding of how to pull the conflict details into their local machines.

Ullas Kishan
2 min read
Unlocking the Secrets of Firebase Authentication with Google in Next.js
Unlocking the Secrets of Firebase Authentication with Google in Next.js

Firebase Authentication is one of its gems, allowing you to add user authentication effortlessly. It's secure, reliable, and comes with Google's seal of approval.

Ullas Kishan
5 min read
[Solved] Firebase auth/invalid-api-key error when setting the values in the environment variable on NextJS?
[Solved] Firebase auth/invalid-api-key error when setting the values in the environment variable on NextJS?

Why am I getting an auth/invalid-api-key error when setting the Firebase values in the environment variable on NextJS ?

Ullas Kishan
2 min read
[Solved] How to download SVG as PNG file
[Solved] How to download SVG as PNG file

Easist way of downloading the SVG file as PNG file is done using javascript snippet

Ullas Kishan
2 min read
Some useful GIT commands for beginners
Some useful GIT commands for beginners

To keep the code is safe and distrubuted between multiple resources that been achieved with the help of GIT

Ullas Kishan
3 min read
How to set the http response headers in NextJS websites
How to set the http response headers in NextJS websites

The importance of the http response headers are highly needed to protect the websites from hackers. If you poorly managed the response header then one day the website will be compromise to the hacker.

Ullas Kishan
3 min read
What are the different types of HTTP Security headers ?
What are the different types of HTTP Security headers ?

An HTTP header is a response by a web server to a browser that is trying to access a web page.

Ullas Kishan
4 min read
[Solved] How to create Application insight access token
[Solved] How to create Application insight access token

Application Insights is an feature of Azure Monitor and it provides application performance monitoring features. APM tools are very useful to analyse applications from development, testing and production release.

Ullas Kishan
2 min read
How to do lazy loading in ReactJS
How to do lazy loading in ReactJS

A lazy function lets you defer the loading of a components code until it is rendered for the first time. Before, it will remain in the bundle. So that we can reduce the load of the application.

Ullas Kishan
3 min read
Javascript interview questions and answers
Javascript interview questions and answers

We covered most asked questions for Javascript interview and their answers

Ullas Kishan
8 min read
How to insert emojis to the html page
How to insert emojis to the html page

we are displaying these emojis with the help of ASCII code and it is not that easy to remember because its a mix of numeric and special characters.

Ullas Kishan
2 min read
What are ES6 features ?
What are ES6 features ?

ES6 or the ECMAScript 2015 is the major edition of ECMAScript language, it introduced several new features which are very special to the developers

Ullas Kishan
7 min read
Different versions of the ECMAscript
Different versions of the ECMAscript

what are the new features among the various versions of ECMA script and what is difference

Ullas Kishan
2 min read
[Solved] How to squash the number of commits from a branch in Git
[Solved] How to squash the number of commits from a branch in Git

We can squash the number of commits from a git branch

Ullas Kishan
3 min read
[Solved] Your focus-trap must have at least one container with at least one tabbable node in it at all times
[Solved] Your focus-trap must have at least one container with at least one tabbable node in it at all times

Your focus-trap must have at least one container with at least one tabbable node in it at all times, when using dialog or modal in ReactJS or other front-end framework

Ullas Kishan
2 min read
Writing test cases for modal popup in Jest
Writing test cases for modal popup in Jest

Writing test cases for modal popup in jest

Ullas Kishan
2 min read
[Solved] Uncaught TypeError: Cannot read property 'location' of undefined
[Solved] Uncaught TypeError: Cannot read property 'location' of undefined

Cannot read property location of undefined, this is an common test cases error in react jest while using useLocation hook in your react component

Ullas Kishan
2 min read
[Solved] Missing ID attributes in markdown to html
[Solved] Missing ID attributes in markdown to html

There is a common problem when parsing the markdown file the ID attribute is missing in the element, here we found a solution to fix/overcome

Ullas Kishan
1 min read
Back to basics : Top interview logical programs in javascript
Back to basics : Top interview logical programs in javascript

It is basicall demonstrating how to find the fibanocci, amstrong, prime numbers and pyramid pattern using javascript.

Ullas Kishan
4 min read
How to read the markdown files in ReactJS
How to read the markdown files in ReactJS

Markdown is a lightweight markup language that you can use to add formatting elements to plaintext text documents.

Ullas Kishan
2 min read
Some useful techniques for array operation using javascript
Some useful techniques for array operation using javascript

There are few development tips for Javascript array operation, these tips will reduce your development time.

Ullas Kishan
3 min read
How to setup auto generated sitemap in nextjs
How to setup auto generated sitemap in nextjs

For every website the Sitemap will be playing important role for SEO performance. In Ecommerce and other consumer websites also SEO have important role for developing their revenue.

Ullas Kishan
3 min read
How to know whether we are using mobile or desktop
How to know whether we are using mobile or desktop

This question is very usual, to get solve this issue by using the browser property user agent to check whether the device type.

Ullas Kishan
1 min read
What are the possible ways to create objects in JavaScript
What are the possible ways to create objects in JavaScript

What are the possible ways to create objects in JavaScript, The traditional way to create an empty object is using the Object constructor. But currently this approach is not recommended.

Ullas Kishan
2 min read