Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Custom Environments with TypeScript #1445

Closed
stangerjm opened this issue Mar 24, 2020 · 13 comments
Closed

Custom Environments with TypeScript #1445

stangerjm opened this issue Mar 24, 2020 · 13 comments

Comments

@stangerjm
Copy link

stangerjm commented Mar 24, 2020

I have checked the troubleshooting guide, it does not solve this issue.

Issue :

When creating a custom environment in TypeScript, Jest throws an error complaining about the TypeScript syntax. It appears that the custom environment is not being compiled.

Expected behavior :

FAIL  tests/ticket-search/advanced-search.spec.ts
  ● Test suite failed to run
      custom-environment.ts:9
          async setup(): Promise<void> {
                       ^
          SyntaxError: Unexpected token ':'
              at node_modules/jest-runner/build/runTest.js:259:7

Debug log:

log file content

N/A

jest.config.js

module.exports = {
  preset: 'ts-jest',
  testMatch: [
    '<rootDir>/tests/**/*.spec.ts',
  ],
  testRunner: 'jest-circus/runner',
  testEnvironment: './scripts/custom-environment.ts',
  moduleDirectories: [
    '.',
    './node_modules',
    './utils',
    './interfaces',
  ],
...
};

Minimal repo

https://github.com/stangerjm/ts-jest-custom-env

npm install
npx jest
@ahnpnl
Copy link
Collaborator

ahnpnl commented Mar 26, 2020

hi, this issue doesn't belong to ts-jest scope. You should check with jest team whether or not they support custom environment with ts. If they support it and pass it to transformer, ts-jest will then can handle it.

I would suggest you to open the issue for jest team.

@ahnpnl ahnpnl closed this as completed Mar 26, 2020
@ahnpnl
Copy link
Collaborator

ahnpnl commented Mar 26, 2020

tag @SimenB has jest already taken into account of this feature ?

@SimenB
Copy link
Contributor

SimenB commented Mar 26, 2020

It will be supported in Jest 26: jestjs/jest#8751

@stangerjm
Copy link
Author

This is fantastic, thanks for pointing this out!

@fsevenm
Copy link

fsevenm commented Dec 16, 2020

It will be supported in Jest 26: facebook/jest#8751

I don't know what did you mean it will be supported. I am using jest 26.6.1 but still getting this error

 FAIL  tests/topup-package/topup-package.spec.ts
  ● Test suite failed to run

    /home/fsevenm/nodejs-projects/deliverit/tests/test-environment.ts:1
    import NodeEnvironment from "jest-environment-node";
    ^^^^^^

    SyntaxError: Cannot use import statement outside a module

      at runTestInternal (node_modules/jest-runner/build/runTest.js:223:5)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        0.025 s
// test-environment.ts
import NodeEnvironment from "jest-environment-node";
import { createUser, destroyUsers } from "./utils";

class TestEnvironment extends NodeEnvironment {
  async setup(): Promise<void> {
    await super.setup();
    const { token } = await createUser();

    this.global.authToken = token;
  }

  async teardown(): Promise<void> {
    await destroyUsers();
    await super.teardown();
  }
}

export default TestEnvironment;
// jest.config.js
module.exports = {
  preset: "ts-jest",
  testEnvironment: "<rootDir>/tests/test-environment.ts",
  moduleNameMapper: {
    "@src/(.*)$": "<rootDir>/src/$1",
  },
  testPathIgnorePatterns: ["/node_modules/", "<rootDir>/build/"],
  globalTeardown: "<rootDir>/tests/teardown.ts",
};

@SimenB
Copy link
Contributor

SimenB commented Dec 16, 2020

it didn't land in 26, but it will be in v27 (you can test it by installing jest@next)

@apgapg
Copy link
Contributor

apgapg commented Aug 1, 2021

This doesn't work. as it starts throwing Cannot use import statement outside a module.
Because testEnvironment is missing in config hence i dont think its wise to use environment with js config. This shall work only with jest.config.ts

@apgapg
Copy link
Contributor

apgapg commented Aug 1, 2021

Because jest@27 is already released hence this issue should be reopened

@ahnpnl
Copy link
Collaborator

ahnpnl commented Aug 1, 2021

If Jest doesn’t pass it to ts-jest, ts-jest cannot compile. I’d suggest you to debug and check first if Jest does correctly.

@apgapg
Copy link
Contributor

apgapg commented Aug 1, 2021

@ahnpnl Okay let me check with jest alone

@apgapg
Copy link
Contributor

apgapg commented Aug 1, 2021

Here is my jest.config.ts

// jest.config.ts
import type { InitialOptionsTsJest } from "ts-jest/dist/types";

const config: InitialOptionsTsJest = {
  // testEnvironment: "./tests/my-environment.ts",
  preset: "ts-jest",
  testPathIgnorePatterns: ["dist"],
  globalSetup: "./tests/setup.ts",
  globalTeardown: "./tests/global.teardown.ts",
  testTimeout: 30000,
  globals: {
    "ts-jest": {},
  },
};
export default config;

The above code works fine.
As soon as I try to uncomment testEnvironment and comment globalSetup, globalTeardown, Error starts occuring saying
Cannot use import statement outside a module

Here is my my-environment.ts

import NodeEnvironment from "jest-environment-node";
import { closeDbConnection, initDbConnection } from "../src/db/dbConnector";
import request from "supertest";
import app from "../src/app/app";

const idToken =<my-token>

class CustomEnvironment extends NodeEnvironment {
  async setup(): Promise<void> {
    await initDbConnection(() => {
      throw new Error("Database connection error, please try again later");
    }, null);
    const response = await request(app).get(`/api/v1/login/exchangeToken?idToken=${idToken}`);
    process.env.cookie = response.headers["set-cookie"];
    return super.setup();
  }

  async teardown() {
    await closeDbConnection();
    await super.teardown();
  }
}

module.exports = CustomEnvironment;

This error links to my code in src folder. Looks like there is some ts issue when accessing src code.
Am I missing something here?

@ahnpnl
Copy link
Collaborator

ahnpnl commented Aug 1, 2021

I could see the my-environment.ts is landed on ts-jest while debugging.

// my-environment.ts
import type {Config} from '@jest/types';
import NodeEnvironment from 'jest-environment-node';

export default class CustomEnvironment extends NodeEnvironment {
  constructor(config: Config.ProjectConfig) {
    super(config);
    this.global.one = 1;
  }
}
// jest.config.js
module.exports = {
  testEnvironment: "<rootDir>/my-environment.ts",
  preset: "ts-jest",
};

One note is: you need to set TypeScript target: ES2015, target: ES5 will throw error

TypeError: Class constructor NodeEnvironment cannot be invoked without 'new'



      at new CustomEnvironment (my-environment.ts:24:28)

Looking at your files, I don't see anything strange, not sure why it doesn't work for your case.

You can check out my repo example here https://github.com/ahnpnl/ts-jest-only-example

@ciclentfort
Copy link

I ran into the same problem. I noticed that jest-environment-node exports an actual class (like uses the class-keyword in the package in node_modules), running the testEnvironment file through ts-jest turns the "CustomEnvironment" into a function.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

6 participants