Typescript Jest ReferenceError: exports is not defined
Asked Answered
C

1

6

I am trying to use jest to start unit testing and I came across this error like this one.

> npm run unit


> [email protected] unit
> NODE_OPTIONS=--experimental-vm-modules jest --config jest.config.ts

 FAIL  tests/unit/get.test.ts
  ● Test suite failed to run

    ReferenceError: exports is not defined

      1 | import { describe, expect, it } from '@jest/globals';
    > 2 | import { APIGatewayProxyEvent, Context } from 'aws-lambda';
        |                       ^
      3 | import { lambdaHandler } from '../../app/app';
      4 |
      5 | describe('Unit test for syncAppInfoToAamDb', () => {

      at tests/unit/get.test.ts:2:23

Here is my code.

import { describe, expect, it } from '@jest/globals';
import { APIGatewayProxyEvent, Context } from 'aws-lambda';
import { lambdaHandler } from '../../app/app';

describe('Unit test for test', () => {
    it('test', async () => {
        ....
        
        const res = lambdaHandler(event, context);
        expect(res).toEqual('test');
    });
});

Earlier I asked here about Jest encountered an unexpected token and modified jest.config.ts

Jest encountered an unexpected token For Typescrip

// jest.config.ts

export default {
    preset: 'ts-jest/presets/default-esm',
    transform: {
        '^.+\\.ts?$': 'ts-jest',
    },
    clearMocks: true,
    collectCoverage: true,
    coverageDirectory: 'coverage',
    coverageProvider: 'v8',
    testMatch: ['**/tests/unit/*.test.ts'],
    testPathIgnorePatterns: ['cf/.aws-sam/build'],
    moduleNameMapper: {
        '^/opt/nodejs/dist/db(.*)$': '<rootDir>/../../nodeLayer/db/dist/db$1',
    },
};

Since jest said that it supports the commonjs format by default, we decided to add preset: 'ts-jest/presets/default-esm'.

What is the cause of this problem? Please tell me if there is a problem with another file. I will include the descriptions of the other files.

Caponize answered 22/8, 2023 at 11:15 Comment(2)
npm install aws-lambda?Riser
No, I have already installed aws-lambda.The same error occurs when the import statement is changed.Caponize
B
1

Based on the official doc:

  1. if you are using a custom transform you should remove the preset config
  2. transform config should include the useESM option
  3. moduleNameMapper config is missing this regex: '^(\\.{1,2}/.*)\\.js$': '$1'
  4. extensionsToTreatAsEsm config is missing

this is my jest.config.ts:

import type { JestConfigWithTsJest } from "ts-jest";

const config: JestConfigWithTsJest = {
  verbose: true,
  transform: {
    "^.+\\.ts?$": [
      "ts-jest",
      {
        useESM: true,
      },
    ],
  },
  extensionsToTreatAsEsm: [".ts"],
  moduleNameMapper: {
    "^(\\.{1,2}/.*)\\.js$": "$1",
  },
};

export default config;
Barabbas answered 28/8, 2023 at 18:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.