I am trying to run some tests for some of. the methods that are used to make a call to an API. I am using Jest on Next.js 14.
My jest.config.js is:
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);
And my jestconfig.json is:
{
"compilerOptions": {
"module": "esnext",
"moduleResolution": "bundler",
"baseUrl": "./",
"paths": {
"@/*": ["./src/*"]
}
}
}
I created a “test” folder in the root of the project and inside of it, I created the test:
import { getRanking, createRanking, updateRanking } from "@/lib/apiCalls";
describe("getRanking function", () => {
beforeEach(() => {
fetchMock.mockClear();
});
it("fetches data successfully", async () => {
const mockData = [{ id: 1, name: "Player A", score: 100 }];
fetchMock.mockResolvedValueOnce({
json: async () => mockData,
});
const result = await getRanking();
expect(result).toEqual(mockData[0]);
expect(fetchMock).toHaveBeenCalledTimes(1);
expect(fetchMock).toHaveBeenCalledWith(
process.env.NEXT_PUBLIC_RANKING_API_URL,
{
method: "GET",
headers: {
"content-type": "application/json",
},
}
);
});
it("handles errors", async () => {
fetchMock.mockRejectedValueOnce(new Error("API is down"));
const result = await getRanking();
expect(result).toBeUndefined();
expect(console.log).toHaveBeenCalledWith(new Error("API is down"));
});
});
describe("createRanking function", () => {
beforeEach(() => {
fetchMock.mockClear();
});
it("creates ranking successfully", async () => {
fetchMock.mockResolvedValueOnce({
json: async () => ({ success: true }),
});
await createRanking();
expect(fetchMock).toHaveBeenCalledTimes(1);
expect(fetchMock).toHaveBeenCalledWith(
process.env.NEXT_PUBLIC_RANKING_API_URL,
{
method: "POST",
headers: {
"content-type": "application/json",
},
}
);
});
it("handles errors", async () => {
fetchMock.mockRejectedValueOnce(new Error("Failed to create ranking"));
await createRanking();
expect(console.log).toHaveBeenCalledWith(
new Error("Failed to create ranking")
);
});
});
describe("updateRanking function", () => {
beforeEach(() => {
fetchMock.mockClear();
});
it("updates ranking successfully", async () => {
const mockWinner = "Player B";
const mockRanking = [{ id: 1, name: "Player A", score: 100 }];
fetchMock.mockResolvedValueOnce({
json: async () => ({ success: true }),
});
await updateRanking(mockWinner, mockRanking);
expect(fetchMock).toHaveBeenCalledTimes(1);
expect(fetchMock).toHaveBeenCalledWith(
process.env.NEXT_PUBLIC_RANKING_API_URL,
{
method: "PUT",
body: JSON.stringify({
winner: mockWinner,
ranking: mockRanking,
}),
headers: {
"content-type": "application/json",
},
}
);
});
it("handles errors", async () => {
const mockWinner = "Player B";
const mockRanking = [{ id: 1, name: "Player A", score: 100 }];
fetchMock.mockRejectedValueOnce(new Error("Failed to update ranking"));
await updateRanking(mockWinner, mockRanking);
expect(console.log).toHaveBeenCalledWith(
new Error("Failed to update ranking")
);
});
});
The file, apiCalls.js, that I want to test contains three methods:
import mongoose from "mongoose";
export const getRanking = async () => {
try {
const res = await fetch(process.env.NEXT_PUBLIC_RANKING_API_URL, {
method: "GET",
headers: {
"content-type": "application/json",
},
});
const data = await res.json();
if (data) return data[0];
return;
} catch (error) {
console.log(error);
}
};
export const createRanking = async () => {
try {
const res = await fetch(process.env.NEXT_PUBLIC_RANKING_API_URL, {
method: "POST",
headers: {
"content-type": "application/json",
},
});
const data = await res.json();
} catch (error) {
console.log(error);
}
};
export const updateRanking = async (winner, ranking) => {
const args = {
winner: winner,
ranking: ranking,
};
try {
const res = await fetch(process.env.NEXT_PUBLIC_RANKING_API_URL, {
method: "PUT",
body: JSON.stringify(args),
headers: {
"content-type": "application/json",
},
});
const data = await res.json();
} catch (error) {
console.log(error);
}
};
When I run the test, it just shows me the following error:
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 | },
I have never used Jest and I do not know what is happening…
I tried to changed the values of jest.config.js and jestconfig.json files, but the error persists
Thanks in advance for the help!