Encountered an error saying 'TextEncoder is not defined' when running Jest in Next.js version 14

I am currently working on testing some API call methods using Jest in a Next.js 14 environment.

Below is my jest.config.js file:

const nextJest = require("next/jest");

/** @type {import('jest').Config} */
const createJestConfig = nextJest({
  // Provide the path to your Next.js app to load next.config.js and .env files in your test environment
  dir: "./",
});

// Add any custom config to be passed to Jest
const config = {
  coverageProvider: "v8",
  testEnvironment: "jsdom",
  moduleNameMapper: {
    "^@/components/(.*)$": "<rootDir>/components/$1",
    "^@/lib/(.*)$": "<rootDir>/lib/$1",
  },
};

// createJestConfig is exported this way to ensure that next/jest can load the Next.js config which is async
module.exports = createJestConfig(config);

As for my jestconfig.json file:

{
  "compilerOptions": {
    "module": "esnext",
    "moduleResolution": "bundler",
    "baseUrl": "./",
    "paths": {
      "@/*": ["./src/*"]
    }
  }
}

To test the methods, I created a "test" folder in the project root and added the following tests:

import { getRanking, createRanking, updateRanking } from "@/lib/apiCalls";

describe("getRanking function", () => {
  // Test cases for getRanking function
});

describe("createRanking function", () => {
  // Test cases for createRanking function
});

describe("updateRanking function", () => {
  // Test cases for updateRanking function
});

The apiCalls.js file, which contains the methods to be tested, includes three functions:

import mongoose from "mongoose";

export const getRanking = async () => {
  // Implementation of getRanking function
};

export const createRanking = async () => {
  // Implementation of createRanking function
};

export const updateRanking = async (winner, ranking) => {
  // Implementation of updateRanking function
};

During testing, I encountered the error message:

ReferenceError: TextEncoder is not defined
      20 |   try {
      21 |     const res = await fetch(process.env.NEXT_PUBLIC_RANKING_API_URL, {
    > 22 |       method: "POST",
         |                                                    ^
      23 |       headers: {
      24 |         "content-type": "application/json",
      25 |       },

This error is new to me, and I'm not sure how to resolve it. I attempted to modify the jest.config.js and jestconfig.json files, but the issue persists.

Any guidance on this matter would be greatly appreciated. Thank you!

Answer №1

I have encountered a similar issue in the past, although not specifically with Next.js. It appears that you are dealing with a problem that has already been documented here. One potential solution is to include a polyfill for TextEncoder and integrate it into your test environment setup.

  1. First, install text-encoding as a development dependency.
npm install --save-dev text-encoding
  1. Next, create a file named setupEnv.js within your project and include the following code:
TextDecoder = require('text-encoding').TextDecoder;
  1. Finally, add setupEnv.js to the setupFiles configuration in your jest.config.js:
const config = {
  coverageProvider: "v8",
  testEnvironment: "jsdom",
  moduleNameMapper: {
    "^@/components/(.*)$": "<rootDir>/components/$1",
    "^@/lib/(.*)$": "<rootDir>/lib/$1",
  },
  setupFiles: ['path/to/setupEnv.js'],
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Trigger price update in jquery based on radio or checkbox selection and specific conditions

https://i.sstatic.net/OIvgF.png In my product form, I have implemented a feature where selecting the "product type" and "product size" will update the price. However, if the user changes the product type after selecting the size, the price does not update ...

Discovering the audio file URL hidden within javascript code

Is it possible to programmatically locate a link to an audio pronunciation clip on a website? I am in the process of creating a personalized language learning Anki deck. The specific site I am referring to is: When clicking on "Framburður," the audio cli ...

How can you personalize the dropdown button in dx-toolbar using DevExtreme?

Currently, I am working with the DevExtreme(v20.1.4) toolbar component within Angular(v8.2.14). However, when implementing a dx-toolbar and specifying locateInMenu="always" for the toolbar items, a dropdown button featuring the dx-icon-overflow i ...

The size of Bootstrap 3 columns adjusts dynamically based on the width of the window as the page is being

I am facing an issue with the layout of my bootstrap site when resizing the 3 horizontal columns based on the window size upon page load. Currently, I have a script that adjusts the height of each column to match the tallest one so they appear uniform whe ...

transform nested object into a flat object using JavaScript

here is the given JSON format: - { "_id": "5c1c4b2defb4ab11f801f30d", "name": "Ray15", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="afddced69e9aefc8c2cec6c381ccc0c2">[email protected]</a>" ...

My JavaScript seems to be having an issue with .className - can anyone help me troubleshoot

I'm currently working on a navigation menu, and my objective is to have the class change to .nav-link-active when a link is clicked, while also reverting the current .nav-link-active back to .nav-link. Here's the code snippet I am using: <he ...

Utilize JavaScript to append a CSS class to a dynamic unordered list item anchor element

I am working with a list of ul li in a div where I need to dynamically add CSS classes based on the click event of an anchor tag. Below is the HTML structure of the ul li elements: <div class="tabs1"> <ul> <li class="active"> ...

Encountering an issue when trying to download a PDF from an Angular 6 frontend using a Spring Boot API - receiving an error related to

When I directly call the Spring Boot API in the browser, it successfully creates and downloads a PDF report. However, when I try to make the same GET request from Angular 6, I encounter the following error: Here is the code snippet for the Spring Boot (Ja ...

Identify the individual who accessed a hyperlink within an email

My team is planning a small experiment involving sending an email to around 50 employees. The email will contain a link to a website stored on our local server, and I want to be able to track exactly who clicks the link by matching it with their email addr ...

Translating Bootstrap 5 into Angular components for version 13 and above

In Angular, the lack of support for optional host-elements and containerless components means that each component comes with its own div wrapper. However, when designing Bootstrap components, a host-less component (without an extra div) is needed to mainta ...

Using JavaScript to obtain the coordinates of a click event from a programmatically triggered click on an HTML element

Is there a way to programmatically simulate a click event on an HTML DOM element and still retrieve the screenX/screenY and clientX/clientY coordinates successfully? When manually clicking the element, the coordinates are visible in the console, but when t ...

Updating a list of books from a form in another component: Step-by-step guide

Hello everyone, I am fairly new to using React and am currently following a tutorial on creating a book library. In this project, I have an AddNewBook Component which is essentially a form structured as follows: function AddNewBook(){ const [name, setNam ...

The function "useLocation" can only be utilized within the scope of a <RouterProvider> in react-router. An Uncaught Error is thrown when trying to use useLocation() outside of a <Router>

When attempting to utilize the useLocation hook in my component, I encountered an error: import React, { useEffect } from 'react'; import { useLocation } from 'react-router-dom'; import { connect } from 'react-redux'; import { ...

What is the process for invoking a server-side C# method from AJAX while transmitting parameters to the function using CommandArgument?

My C# method is responsible for saving data to a SQL Server. It is called from an Onlick event, passing parameters using CommandArgument. Here is an example: <asp:LinkButton runat="server" onClick="save" CommandArgument='<%# Eval("post_id").ToS ...

Executing a mutation upon mounting using React Apollo 2.1's Mutation component: A Step-by-Step Guide

Currently transitioning from Relay to React Apollo 2.1, and I've encountered a questionable situation. Situation: Certain components should only be displayed if the user is authenticated with an API key. To handle this, there's an Authenticator ...

Eliminate square brackets from URL containing an array of IDs using Request.js

My nodejs express application is sending requests with an array parameter, but it's including '[]' in the query string: For example: /foo?id=1&id=3&id=5 How can I remove the square brackets '[]' from the query string? va ...

Issue: User is being redirected from "/login" to "/home" due to a navigation guard. This problem arises in the interaction between Vue-router and Firebase authentication

I'm currently working on an app that utilizes Vue.js and Firebase for authentication. I am trying to implement a verification process using the beforeEach method in my router file to ensure that users can only sign in if their displayName matches a sp ...

Rotate arrows by 90 degrees instead of 180 degrees in Bootstrap 5 Accordion

I have customized a Bootstrap 5 Accordion according to the guide provided at https://getbootstrap.com/docs/5.0/components/accordion/. The default behavior rotates the arrows 180 degrees when an item is opened, changing from 'v' to '^'. ...

Why is the axios.get promise not getting resolved?

I am currently working on fetching data from MongoDB atlas within a React app. However, despite using .then and .catch with axios.get(), I am encountering an unresolved promise. Here is the code snippet: const entry = axios.get('http://localhost:3001 ...

Error when saving data in database (MongoDB) due to a bug

When setting up a database schema, sometimes an error occurs in the console indicating that something was not written correctly. How can this be resolved? Here is the code: let mongoose = require(`mongoose`); let Schema = mongoose.Schema; let newOrder = ...