How to Use Node.js Test Runner: A Detailed Guide

Bonnie

Posted On: October 30, 2024

view count6106 Views

Read time11 Min Read

The JavaScript test runner or Node.js test runner helps automate the testing process for websites and web applications by enabling a range of testing techniques, including unit, integration, and end-to-end testing.

The Node.js test runner automates running tests and offers feedback on the results to help identify and resolve bugs during the stages of software development effectively.

In this blog, we look at how to leverage Node.js test runner for automated testing while exploring methods such as mocking and parallel testing alongside test hooks.

What Is Node.js Test Runner?

Programming languages like Python, Ruby, and Go had a built-in test runner, but JavaScript did not have one. All test runners in the JavaScript ecosystem, such as Mocha, Jest, and Jasmine, were built as third-party packages.

All this changed when Node.js released an experimental built-in test runner in Node.js version 18 and made the test runner stable in Node.js version 20.

The test runner offers several features, such as:

  • Assertion library
  • Test hooks
  • Mocking functionality
  • Code coverage
  • Test reporters
  • Asynchronous testing

Why Use Node.js Test Runner?

The native test runner in Node.js provides several advantages for JavaScript automation testing. Outlined below are some of the benefits of utilizing this test runner:

  • The test runner streamlines the testing process for developers and testers by saving time in deciding which tool to use, as it is integrated within Node.js itself.
  • The built-in assertion library in the Node.js test runner simplifies the process of writing tests and obtaining test results without the need to install other assertion libraries.
  • The test runner includes a feature for code coverage to make sure that all sections of the code are tested by pinpointing the parts that have not been tested yet.
  • The native test runner has a feature called watch mode that allows it to monitor changes in test files and their dependencies. If any changes are detected, the test runner will automatically rerun the tests affected by the modification.
  • Testing using Node.js enables the use of mocks, stubs, and spies that are important for testing individual components in isolation from the entire software.
Info Note

Run Node.js tests across 3000+ real environments. Try LambdaTest Today!

How to Get Started With Node.js Test Runner?

In this part of the blog post, you will learn how to start using the Node.js built-in test runner and run your testing script successfully.

To get started, follow these instructions;

  1. Make sure to use Node.js version 20 or above because the test runner has been completely integrated into the core of Node.js since the release of version 20.
  2. Create a TestRunner directory and launch it using your Integrated Development Environment (IDE). For instance, in this scenario, we have used VS Code.
  3. Run the following command in the terminal to set up a Node.js project:
  4. Create two new folders named src and tests in the TestRunner directory.
  5. Update the test script in your package.json file with the following code snippet:

  6. Install Selenium WebDriver by running the command below:

  7. Run the below-given command to install ChromeDriver:

  8. Create a new started.test.js file in the tests folder. Then, add the following code to the file:

    The above code imports the required functions from node:test and node:assert and describes a simple test that navigates to Google and verifies the title.

  9. Run the below-given command to execute the test:

Using describe() and it() Blocks

In Node.js test runner, you can use describe() and it() blocks to run tests. The describe() block is used to declare a suite that organizes and groups related tests together, while the it() block is used to declare a test.

The benefit of using describe()/it() blocks is that it provides a way to organize your tests into blocks of related functionality or features. This is useful for larger test suites, where you want to keep tests neatly organized and logically grouped.

Inside a describe() block, you can have multiple test() or it() blocks that define specific test cases. You can also nest describe() blocks within each other to create sub-groups of tests for more detailed organization.

You can write tests using describe() and it() blocks, as shown below.

  1. Create a describeit.test.js file within the tests directory and insert the provided code snippet below:

  2. Run the below-given command to execute the test:

Skipping Tests

The Node.js test runner also allows you to skip tests. You can skip tests if they are flaky, the feature being tested is under active development, the test is dependent on unavailable external dependencies, or tests are on deprecated features.

Individual tests can be skipped by passing the skip option to the test or by calling the test context’s skip() annotation. Annotations to avoid running the test in the built-in test runner consist of indicators, like skip:true, skip;’This test is skipped’, t.skip(), and t.skip(“This test is skipped”) as illustrated in this example.

  1. Create a skipping.test.js file within the tests directory and insert the provided code snippet below.

  2. Run the below-given command to execute the test:

Using Test Hooks

The Node.js test runner provides different test hooks. Hooks are functions that run immediately before or immediately after a test. The hooks available in the Node.js test runner are before(), beforeEach(), after(), and afterEach().

Here are some examples of how to use these hooks:

before() Hook

The before() hook is used to prepare the testing environment where it runs once before all the tests in a describe block. For example, you can use the before() hook to set up the WebDriver before all your tests are executed.

Below is how to use the before() hook:

  1. Create a beforehook.test.js file within the tests directory and insert the provided code snippet below:

  2. Run the below-given command to execute the test:

beforeEach() Hook

The beforeEach() hook runs once before each test, where it is used to isolate tests so they do not affect each other. For example, if you have to visit a specific page URL for a couple of tests, you can use a beforeEach() hook to open the URL page before each test is executed.

Below is how to use the beforeEach() hook:

  1. Create a beforeEachhook.test.js file within the tests directory and insert the provided code snippet below:

  2. Run the below-given command to execute the test:

after() Hook

The after() hook runs once after the execution of all the tests where it is used to perform cleanup actions after all the tests are executed. For example, if you want to close the WebDriver after the tests have been executed, you can use the after() hook.

Below is how to use the after() hook:

  1. Create a afterhook.test.js file within the tests directory and insert the provided code snippet below:

  2. Run the below-given command to execute the test:

afterEach() Hook

The afterEach() hook is run once after each test. It is used to perform cleanup actions after each test. For example, if you want to clear cookies after each test, you can use an afterEach() hook.

  1. Create a afterEachhook.test.js file within the tests directory and insert the provided code snippet below:

  2. Run the below-given command to execute the test:

Implementing Mocks

The built-in mocking functionality of the Node.js test runner enables you to mock and substitute functions during testing situations where external dependencies or third-party packages are being used. It is particularly handy when those dependencies are still in the development phase.

You can use mocking functionality to create spies and stubs. Below is an example that illustrates using mocking functionalities to validate fetching data from an API:

First, install axios, a promise-based HTTP client for the browser and Node.js, using the below-given command:

Then, create an index.js file and add the following code:

The code above implements a MakeRequest class, which has three functions fetchDataFromAPI(), slugifyTitle(), and addToDB().

Then, create a mock.test.js file and add the following code:

In the code above, the fetchDataFromAPI method is mocked from the MakeRequest class.

To prevent the function from making a network request, the mockImplementation() method is used to return a predefined output, which can be tested for specific values.

Finally, mock.method() is used to create a spy to test if the slugifyTitle() function is called. Also, how many times the function is called, and its output is tested based on the title.

Run the tests using the below-given command:

Running Parallel Tests

Node.js test runner allows you to execute multiple tests in parallel and at the same time instead of running them sequentially.

To run tests in parallel in Node.js test runner, you need to pass the concurrency: true parameter as the second argument to the describe() function.

Below is an example of how to run tests in parallel using Node.js native test runner and Selenium using concurrency parameters.

  1. Create a parallel.test.js file in the tests folder and add the following code:

  2. Run the below-given command to run the test:

The above test executions are performed on the local grid. However, to scale your automation testing with Node.js, you can consider using a cloud-based testing approach.

AI-driven test execution platforms like LambdaTest let you run Node.js tests on a scalable automation cloud infrastructure, ensuring compatibility and reliability.

Check out this guide to get started with JavaScript automation with LambdaTest.

Conclusion

In summary, the Node.js test runner offers a lightweight solution for creating and executing automated tests in your web projects. Though it may not include all the functionalities found in popular testing frameworks, its straightforwardness and user-friendly nature make it an excellent option for beginning automated testing.

This blog discusses the features of the Node.js built-in test runner. It covers how to create tests using the describe() function and its syntax while making use of hooks for setup and teardown operations, as well as mocking and running tests in parallel threads concurrently for JavaScript code quality assurance and stability enhancement purposes.

For complex testing situations, you may want to evaluate the default test runner against popular frameworks such as Mocha, Jasmine, or Jest to determine which one best suits your requirements.

Frequently Asked Questions (FAQs)

What is a test runner in JS?

A test runner in JavaScript is a framework that automatically runs tests, tracks the results, and provides reports on the success or failure of those tests.

What is a test runner?

A test runner is a framework that executes automated tests, manages their lifecycle, and reports the outcomes for easier debugging.

What is the purpose of the Node.js server test runner in Cypress?

The Node.js server test runner in Cypress manages test execution, controlling the browser, and handling test logic while interacting with your web application.

Author Profile Author Profile Author Profile

Author’s Profile

Bonnie

I am a Web Developer, Technical Writer, and Content Creator. I help developers become better Technical Writers and Make Money Online.

Blogs: 4



linkedintwitter

Test Your Web Or Mobile Apps On 3000+ Browsers

Signup for free