I am trying to run the following test in jest:
import request from "supertest";
import app from '../../src/app';
import QuestionService from "../../src/api/services/questionService";
import { mockDBQuestions } from './get-question-utils';
// Mock the QuestionService function properly
jest.mock("../../src/api/services/questionService", () => ({
__esModule: true, // Ensure ESM compatibility
default: {
getQuestionsAndAnswers: jest.fn(),
},
}));
describe("fetchAllQuestionsController", () => {
it("should return questions with status 200", async () => {
// Mock DB response
const mockQuestions = mockDBQuestions;
jest.spyOn(QuestionService, "getQuestionsAndAnswers").mockResolvedValue(mockQuestions);
const response = await request(app).get("/questions/fetchQuestions").query({ questionType: "Onboarding" });
expect(response.status).toBe(200);
expect(response.body).toEqual(mockQuestions);
expect(QuestionService.getQuestionsAndAnswers).toHaveBeenCalledWith("Onboarding");
});
it("should return empty set with status 200", async () => {
jest.spyOn(QuestionService, "getQuestionsAndAnswers").mockResolvedValue([]);
const response = await request(app).get("/questions/fetchQuestions").query({ questionType: "abcdef" });
expect(response.status).toBe(200);
expect(response.body).toEqual([]);
expect(QuestionService.getQuestionsAndAnswers).toHaveBeenCalledWith("Onboarding");
});
it("should return status 500 on error", async () => {
jest.spyOn(QuestionService, "getQuestionsAndAnswers").mockRejectedValue(new Error("Internal Server Error"));
const response = await request(app).get("/questions/fetchQuestions").query({ questionType: "Onboarding" });
expect(response.status).toBe(500);
expect(QuestionService.getQuestionsAndAnswers).toHaveBeenCalledWith("Onboarding");
});
});
This is my babel.config.js:
export default {
presets: [
['@babel/preset-env', { targets: { node: 'current' }, modules: false}],
'@babel/preset-typescript',
],
plugins: [
['@babel/plugin-proposal-decorators', { legacy: true }],
['@babel/plugin-transform-flow-strip-types'],
['@babel/plugin-proposal-class-properties', { loose: true }],
],
};
This is my test.config.js file :
export default {
preset: 'ts-jest/presets/default-esm',
testEnvironment: 'node',
testMatch: ['**/tests/**/*.test.ts'],
moduleFileExtensions: ['ts', 'js', 'json', 'node', 'mjs', 'cjs'],
transform: {
'^.+\.ts$': [
'ts-jest',
{
useESM: true, // Ensuring Jest treats TS as ESM
},
],
},
extensionsToTreatAsEsm: ['.ts'],
transformIgnorePatterns: ['node_modules/(?!supertest/)'], // Transpile 'supertest' if needed
globals: {
'ts-jest': {
tsconfig: 'tsconfig.json',
useESM: true,
},
},
setupFilesAfterEnv: ['./jest.setup.ts'], // Ensure Jest setup is working
};
This is my package.json file starting :
"name": "backendtemplate",
"version": "1.0.0",
"main": "index.js",
"type": "module",
"jest": {
"transform": {}
},
and this is my tsconfig.json:
{
"compilerOptions": {
"target": "ESNext",
"module": "ESNext",
"outDir": "./dist",
"rootDir": "./src",
"esModuleInterop": true,
"moduleResolution": "node",
"resolveJsonModule": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"useDefineForClassFields": false,
"allowSyntheticDefaultImports": true,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"allowImportingTsExtensions": true,
"strict": true,
"noImplicitAny": true,
"strictNullChecks": true,
"skipLibCheck": true,
"sourceMap": true,
"removeComments": true,
"noEmitOnError": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noImplicitReturns": true,
"types": ["node"],
"strictPropertyInitialization": false,
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}
I am getting the following error when trying to run my test case:
(dev-serve/api) [dynodatingappbe:user_profile_edit_api] % npm run test
> [email protected] test
> jest
PASS tests/UserProfileEditModule/update-user-profile.test.ts
PASS tests/server.test.ts
FAIL tests/QuestionModule/get-questions.test.ts
● Test suite failed to run
Jest encountered an unexpected token
Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.
Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.
By default "node_modules" folder is ignored by transformers.
Here's what you can do:
• If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
• If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
• To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
• If you need a custom transformation specify a "transform" option in your config.
• If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.
You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/configuration
For information about custom transformations, see:
https://jestjs.io/docs/code-transformation
Details:
/Users/rahul.negi/personal/Dyno/dynodatingappbe/tests/QuestionModule/get-questions.test.ts:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import request from "supertest";
^^^^^^
SyntaxError: Cannot use import statement outside a module
at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1505:14)
Test Suites: 1 failed, 2 passed, 3 total
Tests: 2 passed, 2 total
Snapshots: 0 total
Time: 0.143 s, estimated 1 s
Ran all test suites.
What am I missing which is causing this issue?
So far I have tried the following methods :
- Tried to rename
babel.config.js
tobabel.config.cjs
- Tried to Ensure that
"module": "ESNext"
and"moduleResolution": "node"
are correctly set in tsconfig.json - Tried adding
transformIgnorePatterns: ['node_modules/(?!supertest/)'],
intest.config.js
file.