Getting Error On Running Jest Test:
ReferenceError: You are trying to
import` a file after the Jest environment has been torn down. From test/api/agents/index.test.ts.
FAIL test/api/agents/index.test.ts
● Test suite failed to run
SyntaxError: Unexpected token ':'
at Runtime.loadEsmModule (node_modules/jest-runtime/build/index.js:516:20)
ReferenceError: You are trying to import
a file after the Jest environment has been torn down. From test/api/agents/index.test.ts.
test/api/agents/index.test.ts`
test/api/agents/index.test.ts
import { NextApiResponse } from "next";
import { createMocks } from "node-mocks-http";
import { AppNextApiRequest } from "@app/types";
import { getAgents } from "@app/pages/api/agents";
import { respond } from "@app/utils/createa-api-handler";
import { expect, describe, it, jest } from "@jest/globals";
const session = {...}
describe("/api/agents", () => {
it("should get the list of agents.", async () => {
const { req, res } = createMocks<AppNextApiRequest, NextApiResponse>({
session,
method: "GET",
headers: {
"Content-Type": "application/json",
},
});
await respond(getAgents)(req, res);
expect(res._getStatusCode).toBe(200);
}, 6000);
});
jest.config.ts
import type { Config } from "jest";
import nextJest from "next/jest";
const createJestConfig = nextJest({
dir: "./",
});
const config: Config = {
verbose: true,
preset: "ts-jest",
coverageProvider: "v8",
testEnvironment: "node",
moduleDirectories: ["node_modules", "<rootDir>"],
testPathIgnorePatterns: ["/node_modules/", "/.next/", "/packages/"],
fakeTimers: {
enableGlobally: true,
},
transform: {
"^.+\.(ts|tsx)$": [
"ts-jest",
{
useESM: true,
isolatedModules: true,
},
],
},
extensionsToTreatAsEsm: [".ts", ".tsx"],
transformIgnorePatterns: ["/emailer/"],
moduleNameMapper: {
"^@app/(.*)$": "<rootDir>/$1",
},
};
export default createJestConfig(config);
test should run at least.
5