Front-end Development
8 min read

Introduction to Nuxt Test Utils

Here we provide an overview of Nuxt Test Utils, its features, and how to set up a test environment with `nuxt/test-utils`.

David Adeneye
Published August 4, 2022
AI Assistant for Playwright
Code AI-powered test steps with the free ZeroStep JavaScript library
Learn more

Nuxt is a free and open-source JavaScript library built upon Vue that allows you to develop server-rendered web applications. Nuxt Test Utils is a test utility library for Nuxt.js for creating tests for Nuxt projects and modules. It offers several helpful methods for testing Nuxt applications, writing browser tests, and validating module test results.

What is Nuxt Test Utils?

nuxt/test-utils is a test utility library for Nuxt.js that allows you to create tests easily for Nuxt projects and modules. It provides several useful functions and methods for testing Nuxt applications, writing browser tests, and validating the module’s test result.

With the nuxt/tests utils, you can easily set up a testing environment for your Nuxt projects. It offers some helper functions behind the scenes that ensure test environments are set up correctly. The library extends Jest matcher and also exposes a few helpful methods for testing Nuxt applications.

For developers developing Nuxt modules, nuxt/tests-utils offer some helpful methods for validating the module’s test result. When writing tests for a Nuxt module, you usually expect that the module is installed with certain conditions. nuxt/test-utils provides some wrapper methods to assert that a specific method is triggered while installing a module, which we will look into shortly.

nuxt/tests-utils incorporates Playwright under the hood to perform browser testing. Browser testing involves checking how your web application behaves across multiple browsers. Web applications might behave differently across different browsers, something you might not be aware of, and you can only really tell how it works by writing a browser test for it.

Prerequisites

Here are the prerequisites you’ll need to follow along with this tutorial:

Setting up a Nuxt Test Environment with nuxt/test-utils

To get started quickly, we will scaffold a Nuxt application with create-nuxt-app. To do that, navigate into a folder and run the following command:

1
yarn create nuxt-app <project-name>

Running this command will prompt a series of questions, use this template below to answer the questions:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
create-nuxt-app v4.0.0
✨ Generating Nuxt.js project in nuxt-test-utils-demo
   Project name: nuxt-test-utils-demo
   Programming language: JavaScript
   Package manager: Yarn
   UI framework: None
   Nuxt.js modules: (Press <space> to select, <a> to toggle all, <i> to invert selection)
   Linting tools: ESLint
   Testing framework: None
   Rendering mode: Universal (SSR / SSG)
   Deployment target: Server (Node.js hosting)
   Development tools: jsconfig.json (Recommended for VS Code if you're not using typescript)
   Continuous integration: None
   Version control system: Git

After answering all the questions, it will install all the dependencies. Navigate to the project folder and launch it with this command:

1
2
cd <project-name>
yarn dev

Your demo application is now running on http://localhost:3000.

demo

Installing @nuxt/test-utils and configuring with Jest

Nuxt test-utils extend Jest matchers, so we need to install and configure it with Jest. To add nuxt/test-utils and Jest to your project, run the following command below:

1
yarn add --dev @nuxt/test-utils jest

The command will add the libraries as a development dependency.

To configure Jest, create a new file named jest.config.js at the root folder of your project and add @nuxt/test-utils to the preset section:

1
2
3
module.exports = {
  preset: ‘@nuxt/test-utils`
}

For a test run, we need to add a test script to the package.json file:

1
2
3
"scripts": {
    "test": "jest"
},

Setting up test context

To utilize @nuxt/test-utils helper methods in each describe block, you must first set up the test context before starting.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
import { setupTest } from "@nuxt/test-utils";

describe("My test", () => {
  setupTest({
    // test context options
  });

  test("my test", () => {
    // ...
  });
});

The setupTest function performs a series of tasks in beforeEach, afterEach, and afterAll in the background to properly set up the Nuxt test environment. It also adds a single Nuxt setup task as an additional test. Basically, it must be run within the describe block of a test, before any other calls to it or test.

Note: The tests will fail if you use test.only or it.only later in the describe block.

There are several options and features to enable for setupTest:

server: Whether to launch a server to respond to requests in the test suite.

browser: Nuxt Test Utils uses Playwright behind the scenes to perform browser testing. If this option is enabled, a browser will be launched and can be controlled in the subsequent test suites.

You can learn more about other options for setupTest in the Nuxt Test Utils docs.

Testing your Application

The Nuxt test-utils provide some helpful methods to utilize when testing a Nuxt application.

These helper methods are:

Let’s run a simple test to verify that we’ve successfully configured @nuxt/test-utils. Create a folder called tests inside your project, navigate into the folder and create a test file named test.spec.js. Open the test file and insert the following test:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
import { setupTest, url } from "@nuxt/test-utils";

describe("ssr", () => {
  setupTest({ server: true });

  test("renders the index page", async () => {
    const thePage = await url("/");

    // is something like 'http://localhost:5782'
    console.log("URL:", thePage);
  });
});

Run the test with the following command:

1
yarn test

Below is a snapshot of the test result:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
@David-Adeneye-MacBook-Pro-M1 nuxt-test-utils-demo % yarn test
yarn run v1.22.15
$ jest
  console.log
    URL: http://localhost:5412/

      at Object.log (tests/test.spec.js:10:13)

 PASS  tests/test.spec.js
  ssr
    ✓ setup nuxt (4566 ms)
    ✓ renders the index page (9 ms)

Testing for the Browser

By leveraging the power of Playwright, nuxt test-utils allow you to easily carry out browser testing. Playwright is a reliable end-to-end testing tool for the modern web.

Run the following command to add playwright as a dev dependency to your project:

1
yarn add --dev playwright

To set up a test for the browser, it is required that you pass { browser: true } as an option to setupTest.

Run the following command to add playwright as a dev dependency to your project:

1
yarn add --dev playwright

Then create a test file named browser.spec.js inside the tests folder. Open the test file and add the following tests:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
import { setupTest, createPage } from "@nuxt/test-utils";

describe("browser", () => {
  setupTest({ browser: true });

  test("renders the index page and shows heading", async () => {
    const page = await createPage("/");
    const html = await page.innerHTML("body");

    expect(html).toContain(" Welcome to your Nuxt Application");
  });
});

To set up a test for the browser, it is required that you pass { browser: true } as an option to setupTest. Then we use the createPage to initiate a browser session to call the homepage with the route / and assert that our homepage contains the heading “Welcome to your Nuxt Application”.

Run the test with the following command:

1
yarn test browser.spec.js

Below is a snapshot of the test result:

1
2
3
4
5
6
7
@David-Adeneye-MacBook-Pro-M1 nuxt-test-utils-demo % yarn test browser.spec.js
yarn run v1.22.15
$ jest browser.spec.js
 PASS  tests/browser.spec.js (6.834 s)
  browser
    ✓ setup nuxt (5504 ms)
    ✓ renders the index page and display heading (987 ms)

Testing Nuxt Modules

nuxt/test-utils provides a few useful methods for testing Nuxt modules for developers. When writing tests for Nuxt module, you normally expect the module to be installed with certain conditions like to add plugins or to not add a certain plugin while installing Nuxt modules.

Nuxt test-utils offer some wrapper methods to easily validate module test results:

expectModuleToBeCallWith(method, …args)

Below is a sample test template to expect a specific method to be triggered while installing a module:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
import { setupTest, expectModuleToBeCalledWith, getNuxt } from "@nuxt/test-utils";

describe("module", () => {
  setupTest({
    testDir: __dirname,
    fixture: "example",
    config: {
      myModule: {
        test: 123,
      },
    },
  });

  test("should inject plugin", () => {
    expectModuleToBeCalledWith("addPlugin", {
      src: expect.stringContaining("templates/plugin.js"),
      fileName: "myPlugin.js",
      options: getNuxt().options.myModule,
    });
  });
});

Code Source from nuxt/test-util docs

To expect a specific method not to be triggered while installing a method, you can simply use expectModuleNotToBeCall(method, …args) provided by @nuxt/test-utils:

1
2
3
test(should inject plugin`,  ()  =>  {
  expectModuleNotToBeCalledWith(‘addLayout’)
}

Conclusion

In this tutorial, we introduced nuxt test-utils and its main features. Also, we demonstrated how to quickly set up a Nuxt test environment for nuxt projects using @nuxt/test-utils.

Get started with Reflect today

Create your first test in 2 minutes, no installation or setup required. Accelerate your testing efforts with fast and maintainable test suites without writing a line of code.

Copyright © Reflect Software Inc. All Rights Reserved.