javascript - Getting Cannot use import statement outside a module when running test in jest - Stack Overflow

I am trying to run the following test in jest:import request from "supertest";import app fr

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  for how to enable it.
     • If you are trying to use TypeScript, see 
     • 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:
    
    For information about custom transformations, see:
    

    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 :

  1. Tried to rename babel.config.js to babel.config.cjs
  2. Tried to Ensure that "module": "ESNext" and "moduleResolution": "node" are correctly set in tsconfig.json
  3. Tried adding transformIgnorePatterns: ['node_modules/(?!supertest/)'], in test.config.js file.

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 :

  1. Tried to rename babel.config.js to babel.config.cjs
  2. Tried to Ensure that "module": "ESNext" and "moduleResolution": "node" are correctly set in tsconfig.json
  3. Tried adding transformIgnorePatterns: ['node_modules/(?!supertest/)'], in test.config.js file.
Share Improve this question asked Mar 23 at 8:00 Rahul NegiRahul Negi 11 silver badge 1
  • Avoid native esm if you want to use regular jest module mocking like jest.mock – Estus Flask Commented Mar 23 at 8:04
Add a comment  | 

1 Answer 1

Reset to default 1

In your babel.config.js file, remove modules: false.

Updated babel config:

export default {
  presets: [
      ['@babel/preset-env', { targets: { node: 'current' }}], // Changed
      '@babel/preset-typescript',
  ],
  plugins: [
      ['@babel/plugin-proposal-decorators', { legacy: true }],
      ['@babel/plugin-transform-flow-strip-types'],
      ['@babel/plugin-proposal-class-properties', { loose: true }],
  ],
};

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744293375a4567139.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信