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!