Component Testing Next.js Application with Cypress

Traitanit Huangsri
Geek Culture
Published in
7 min readMay 3, 2021

Hi folks! In this article, I’ll show you how to write Component Testing your Next.js applications with Cypress. This could change your testing experience forever.

What is Component Testing?

Nowadays, web development has evolved. We usually design our website using a design pattern called “Web Components” which we can reuse anywhere on the web. Component Testing is a concept that we test the web component in isolation to see its behavior. With this concept, we can focus on only the specific component under test which is a pretty much different perspective comparing to another testing level like integration or end-to-end testing.

Web Components

Normally, we do run the component testing in a Node.js virtual browser like jsdom. This kind of approach has some drawbacks:

  1. The virtual browser does not 100% support all Browser APIs
  2. We cannot even see how the component is rendered. We only see the DOM hierarchy in a text mode.

With Component Testing in Cypress, it runs your web components in the REAL browser with full Browser APIs support. Your components also render and visible to your eyes when it’s running. Is that cool?

Component Testing Next.js applications with Cypress

Since Cypress 7.0, they do support Component Testing with modern web frameworks like React, Vue, and of course Next.js. Next.js is a web framework developed by Vercel to help developers create a more powerful web application. It enhances React to build a static or server-side rendering application and also adds more features to it for example Image Optimization, Smart Code Splitting and Bundling, and many more.

In this article, I’ll show you how to set up and write your first component testing for Next.js applications in step by step.

1. Create Next.js Application

Firstly, let’s create a new Next.js app using a create-next-app tool

$ npx create-next-app nextjs-cypress-ct

After we got a project created, let’s run the simple app

$ yarn dev

And when entering the web at http://localhost:3000, you should see the web is displayed like this

2. Install Cypress and other Test Dependencies

When your Next.js app is ready, then install Cypress and other test libraries as devDependencies

$ yarn add -D cypress @cypress/react @cypress/webpack-dev-server @testing-library/cypress html-webpack-plugin webpack webpack-dev-server

After all of them are installed, your package.json file should be like this

Then, run this command

$ npx cypress open

Cypress will initialize and set up the file structure to your Next.js app

There is a cypress directory at the root directory of your project. It consists of:

  • integration: a folder for integration and end-to-end test cases.
  • fixtures: to store your test data like JSON or mock data file.
  • plugins: for loading Cypress plugins (will use it later in this article)
  • supports: for loading other support files like Cypress Custom Commands

3. Create your Web Component

In this article, I’ll create a simple web component for rendering blog post called “Posts” The data will be fetched from the fake API https://jsonplaceholder.typicode.com/

I also apply best practices for locating web elements by using a separated locator file for the custom data attribute so that I can reuse them later in my tests. For example <h2 data-testing={locators.title}> to load data-testid=’post-title’

Then I edit the home page pages/index.js to add my Posts component to display on the home page

Then I rerun the app to see how my “Posts” component is rendered.

Posts component in Home Page

4. Writing Test for the “Posts” Component

To start writing tests for your web component with Cypress, I create a new folder called “component” under cypress directory to store component test cases here. But first of all, we have to set up some of the libraries to make Cypress be able to access your web components.

4.1 Inject Next.js Component Testing Plugin to Cypress

At cypress/plugin/index.js , inject Next.js Component Testing plugin like this

The plugin will inject Next.js webpack-dev-server to allow Cypress to access your web components.

4.2 Start writing tests

The concept of writing component testing is similar to an end-to-end test except you don’t have to call cy.visit() to navigate to the web page. Instead, you just call mount API to mount the web component and interact with it using Cypress commands.

In this case, I also use Cypress Testing Library to access DOM elements via a custom data attribute called “data-testid” If you’ve tried the React Testing Library, the concept is pretty much the same.

In my “Posts” component, it allows us to pass two properties which are posts and users. So I create a mock object for these two props using the same structure as the response data from the API. Then passing it as props to the component and see the result on how it renders the component.

5. Running Component Testing with Cypress

Cypress has introduced the new test runner called “Component Test Runner” which allow us to manage the component test cases e.g. test filtering and it also adds the React Dev Tools on it (if we have already installed it to the browser) This is super cool because we can use it to debug our component while the test is running. I think this feature is very useful for developers like us.

To run component testing with Cypress, execute the command

$ npx cypress open-ct

Yeah! you can see how your component is rendered. Also, you can trace back to any test step to see what happened. And yes, on the right bottom is a React Dev Tool which helps you to debug your component easier. What a cool test runner!

6. Generate Code Coverage Report

Some of you might curious to know if we can see the code coverage report for the component testing with Cypress? The answer is “Of Course” you can easily generate the code coverage report for your component testing using Cypress Code Coverage Report Plugin. Let’s see how to do it

6.1 Install dependencies

To generate a code coverage report, you have to install these two libraries: Cypress Code Coverage Plugin and Istanbul Babel Plugin (For Code Instrumentation)

$ yarn add -D @cypress/code-coverage babel-plugin-istanbul

6.2 Add Code Coverage Task to Cypress

At cypress/plugins/index.js add the code coverage task to it

Cypress will execute the task every time you run the test automatically.

6.3 Import Code Coverage Plugin

At cypress/supports/index.js import the plugin to it

6.4 Configure Babel Plugin for Code Instrumentation

Create a file name .babelrc in the root directory to configure Istanbul Babel Plugin

6.5 Rerun the Component Testing

When we rerun the tests, there will be a new folder called “coverage” in the root directory of your project. The code coverage report will be displayed as a lcov-report format like this

You can click on your component file to see code coverage in detail

Cool! That’s it. We have a code coverage report to see how many lines of code or statements that the test is covered.

Conclusion

So we can start writing component testing the Next.js application with Cypress easily. With “Cypress Component Test Runner”, helps us to debug the web component easier, visible to your eyes, and running in the REAL browsers. So you don’t have to mock some of browser APIs anymore.

I hope my article can help you to start writing tests for your Next.js app from today. If you want to see the full example of source code, let’s check it out from the link below. Happy Coding and Testing!

--

--