Skip to main content
Redhat Developers  Logo
  • AI

    Get started with AI

    • Red Hat AI
      Accelerate the development and deployment of enterprise AI solutions.
    • AI learning hub
      Explore learning materials and tools, organized by task.
    • AI interactive demos
      Click through scenarios with Red Hat AI, including training LLMs and more.
    • AI/ML learning paths
      Expand your OpenShift AI knowledge using these learning resources.
    • AI quickstarts
      Focused AI use cases designed for fast deployment on Red Hat AI platforms.
    • No-cost AI training
      Foundational Red Hat AI training.

    Featured resources

    • OpenShift AI learning
    • Open source AI for developers
    • AI product application development
    • Open source-powered AI/ML for hybrid cloud
    • AI and Node.js cheat sheet

    Red Hat AI Factory with NVIDIA

    • Red Hat AI Factory with NVIDIA is a co-engineered, enterprise-grade AI solution for building, deploying, and managing AI at scale across hybrid cloud environments.
    • Explore the solution
  • Learn

    Self-guided

    • Documentation
      Find answers, get step-by-step guidance, and learn how to use Red Hat products.
    • Learning paths
      Explore curated walkthroughs for common development tasks.
    • Guided learning
      Receive custom learning paths powered by our AI assistant.
    • See all learning

    Hands-on

    • Developer Sandbox
      Spin up Red Hat's products and technologies without setup or configuration.
    • Interactive labs
      Learn by doing in these hands-on, browser-based experiences.
    • Interactive demos
      Click through product features in these guided tours.

    Browse by topic

    • AI/ML
    • Automation
    • Java
    • Kubernetes
    • Linux
    • See all topics

    Training & certifications

    • Courses and exams
    • Certifications
    • Skills assessments
    • Red Hat Academy
    • Learning subscription
    • Explore training
  • Build

    Get started

    • Red Hat build of Podman Desktop
      A downloadable, local development hub to experiment with our products and builds.
    • Developer Sandbox
      Spin up Red Hat's products and technologies without setup or configuration.

    Download products

    • Access product downloads to start building and testing right away.
    • Red Hat Enterprise Linux
    • Red Hat AI
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform
    • See all products

    Featured

    • Red Hat build of OpenJDK
    • Red Hat JBoss Enterprise Application Platform
    • Red Hat OpenShift Dev Spaces
    • Red Hat Developer Toolset

    References

    • E-books
    • Documentation
    • Cheat sheets
    • Architecture center
  • Community

    Get involved

    • Events
    • Live AI events
    • Red Hat Summit
    • Red Hat Accelerators
    • Community discussions

    Follow along

    • Articles & blogs
    • Developer newsletter
    • Videos
    • Github

    Get help

    • Customer service
    • Customer support
    • Regional contacts
    • Find a partner

    Join the Red Hat Developer program

    • Download Red Hat products and project builds, access support documentation, learning content, and more.
    • Explore the benefits

Introduction to the Node.js reference architecture: Testing

Introduction to the Node.js reference architecture, Part 14

July 27, 2023
Lucas Holmquist
Related topics:
Node.js
Related products:
Red Hat build of Node.jsRed Hat Enterprise Linux

    Welcome back to the Node.js reference architecture series. In this article, we’ll take a look at testing in the Node.js landscape and discuss the guidelines recommended by the Node.js reference architecture team.

    Follow the series:

    • Part 1: Overview of the Node.js reference architecture
    • Part 2: Logging in Node.js
    • Part 3: Code consistency in Node.js
    • Part 4: GraphQL in Node.js
    • Part 5: Building good containers
    • Part 6: Choosing web frameworks
    • Part 7: Code coverage
    • Part 8: Typescript
    • Part 9: Securing Node.js applications
    • Part 10: Accessibility
    • Part 11: Typical development workflows
    • Part 12: npm development
    • Part 13: Problem determination
    • Part 14: Testing
    • Part 15: Transaction handling
    • Part 16: Load balancing, threading, and scaling
    • Part 17: CI/CD best practices in Node.js
    • Part 18: Wrapping up

    2 testing tools

    Testing is probably one of the most important parts of any software development practice. It is also one of the most “I’ll get to that later” parts. And let’s be honest, we never get to it later. One of the reasons that developers have an aversion to testing is trying to figure out what tools to use.

    Like most tasks in software development, the answer to which is the best package to use for testing is, it depends. It depends on the type and scope of the project. Does a one-size-fits-all solution work or should you go with a solution that is a bit more granular? These are the types of questions that the team asked itself when coming up with recommendations. There are two test frameworks that the team has had success with.

    • Jest is a popular testing framework from Meta. It excels at testing React and other component-based web applications, and can be used in other contexts. It is considered an opinionated framework because it provides its own set of assertions, spies/stubs/mocks, and other features (e.g., snapshot testing and code coverage) out of the box.
    • Mocha is a widely used, mature (created in 2011), and stable project. While Node.js is the main area of focus and support, Mocha can also be used in a browser context. Mocha is an un-opinionated framework with a large ecosystem of plugins and extensions.

    Note: The test framework recommendations are part of the OpenJS Foundation.

    These frameworks have advantages, and in the next sections, we will take a look at why you might choose one over the other.

    When Jest is the better tool

    • When testing React or component-based applications.
    • When using a compile-to-JavaScript language (like TypeScript).
    • When snapshots are useful.

    Snapshots provide an easy to use way of testing output of a function and saving the result as a snapshot artifact, which can then be used to compare against as a test. As an example:

    test('unknown service', () => {
    
        expect(() => {
    
          bindings.getBinding('DOEST_NOT_EXIST');
    
        }).toThrowErrorMatchingSnapshot('unknown service');
    
      });

    The first time the test runs, it will create and store a snapshot of the expected exception. On subsequent runs, if the exception does not match the snapshot, it will report a test failure. This makes generating and capturing the result from an operation testing fast and easy.

    When Mocha is the better tool

    • When you want a smaller dependency tree (91 packages versus 522).
    • When Jest's opinions, environment proxies, and dependency upon babel are unfavorable for your use case.

    As an example of potential problems with Jest's environment proxies, Jest replaces globals in the environment in a way that can cause failures with native add-ons. For example, this simple test fails:

    const addon = require('bindings')('hello');
    
    
    
    describe('test suite 1', () => {
    
      test('exception', () => {
    
        expect(addon.exception()).toThrow(TypeError);
    
      });
    
    });

    Even though the add-on is throwing the expected exception, as follows:

    static napi_value ExceptionMethod(napi_env env, napi_callback_info info) {
    
       napi_throw_type_error(env, "code1", "type exception");
    
       return NULL;
    
    }

    The failure reports the exception as TypeError: type exception.

    FAIL  __tests__/test.js
    
      ● test suite 1 › exception
    
        TypeError: type exception
    
          3 | describe('test suite 1', () => {
    
          4 |   test('exception', () => {
    
        > 5 |     expect(addon.exception()).toThrow(TypeError);
    
            |                  ^
    
          6 |   });
    
          7 | });
    
          8 |
    
          at Object.<anonymous> (__tests__/test.js:5:18)

    An equivalent test runs successfully with Mocha. You can review the full source for the test on GitHub.

    Recommended packages to use with Mocha

    Because Mocha is un-opinionated, it does not ship with batteries included. While Mocha is usable without any other third-party library, many users find the following libraries and tools helpful.

    Refer to the mocha documentation and examples repository for more information on integrating with other tools.

    Assertion library

    Most Mocha users will want to consume a third-party assertion library. Besides the Node.js built-in assert module, Mocha recommends choosing one of the following. Both have their own plugin ecosystems.

    • chai: The most popular general-purpose assertion library, with traditional and natural language APIs available.
    • unexpected: A string-based natural language API, Mocha uses Unexpected in its own tests.

    Stubs, spies, and mocks

    Many users will want a library providing stubs, spies, and mocks to aid isolation when writing unit tests. Both have their own plugin ecosystems.

    • sinon: The most popular stub, spy and mock library, and it is mature.
    • testdouble: This is a full-featured library with the ability to mock at the module level.

    Code coverage

    Mocha does not automatically compute code coverage. If you need it, use the following:

    • nyc: The most popular code-coverage tool, and the successor CLI for Istanbul.

    For more on code coverage, review the code coverage section of the Node.js reference architecture. Also, take a look at Part 7 of this article series on code coverage.

    A new feature in Node core

    A recent addition to Node core could also help in determining a developers testing strategy. A test runner is now available in Node core (v18 and v16). With the release of Node 20, it is now considered stable.

    The following is a basic example of how this new test runner can be used:

    const test = require('node:test');
    
    test('asynchronous passing test', async (t) => {
      // This test passes because the Promise returned by the async
      // function is not rejected.
      assert.strictEqual(1, 1);
    });

    Since this is a new addition, the team doesn’t have guidance on this yet, but it is on our radar to reevaluate our current guidance.

    A simpler method

    Before wrapping up, there is one fun and helpful thing that I would like to offer. When running your tests in a CI environment, it is somewhat trivial to specify all the different node versions you would like to test against. This isn’t as easy during development time. Many developers use a Node Version Manager like nvm to switch between different versions of node rather than just their tests.

    There is a slightly simpler way using the npx command (with the -p flag) and the node npm module which will allow you to run a npm script (or any node application) using a different version of node than what is installed locally. For example, to run your applications test suite with Node 18.12.1, the command might look like this:

    npx -p node@18.12.1 -- npm run test

    What’s next?

    We cover new topics regularly as part of the Node.js reference architecture series. Next, read about transaction handling in Node.js.

    We invite you to visit the Node.js reference architecture repository on GitHub, where you can view our work. To learn more about what Red Hat is up to on the Node.js front, check out our Node.js page.

    Last updated: January 9, 2024

    Related Posts

    • Why we developed the Node.js reference architecture

    • Introduction to the Node.js reference architecture, Part 7: Code coverage

    • Introduction to the Node.js reference architecture, Part 3: Code consistency

    • Introduction to the Node.js reference architecture, Part 11: Typical development workflows

    • Monitor Node.js applications on Red Hat OpenShift with Prometheus

    Recent Posts

    • Trusted software factory: Building trust in the agentic AI era

    • Build a zero trust AI pipeline with OpenShift and RHEL CVMs

    • Red Hat Hardened Images: Top 5 benefits for software developers

    • How EvalHub manages two-layer Kubernetes control planes

    • Tekton joins the CNCF as an incubating project

    What’s up next?

    Learn how to deploy an application on a cluster using Red Hat OpenShift Service on AWS. This learning path uses a pre-built application to allow you to become more familiar with OpenShift and Kubernetes features.

    Start learning
    Red Hat Developers logo LinkedIn YouTube Twitter Facebook

    Platforms

    • Red Hat AI
    • Red Hat Enterprise Linux
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform
    • See all products

    Build

    • Developer Sandbox
    • Developer tools
    • Interactive tutorials
    • API catalog

    Quicklinks

    • Learning resources
    • E-books
    • Cheat sheets
    • Blog
    • Events
    • Newsletter

    Communicate

    • About us
    • Contact sales
    • Find a partner
    • Report a website issue
    • Site status dashboard
    • Report a security problem

    RED HAT DEVELOPER

    Build here. Go anywhere.

    We serve the builders. The problem solvers who create careers with code.

    Join us if you’re a developer, software engineer, web designer, front-end designer, UX designer, computer scientist, architect, tester, product manager, project manager or team lead.

    Sign me up

    Red Hat legal and privacy links

    • About Red Hat
    • Jobs
    • Events
    • Locations
    • Contact Red Hat
    • Red Hat Blog
    • Inclusion at Red Hat
    • Cool Stuff Store
    • Red Hat Summit
    © 2026 Red Hat

    Red Hat legal and privacy links

    • Privacy statement
    • Terms of use
    • All policies and guidelines
    • Digital accessibility

    Chat Support

    Please log in with your Red Hat account to access chat support.