Gillis Werrebrouck
Gillis Werrebrouck

Reputation: 449

How to use multiple Jest presets with only one Jest configuration file/setup?

A project I'm working on is already configured with Jest and testing works as it should. This is how the current jest.config.js file looks like;

const ignores = [...];
const coverageIgnores = [...];

module.exports = {
  roots: ['<rootDir>/src'],
  globals: {
    'ts-jest': {
      tsConfig: 'tsconfig.json',
    },
  },
  moduleFileExtensions: ['js', 'json', 'ts'],
  testPathIgnorePatterns: [...ignores],
  coveragePathIgnorePatterns: [...ignores, ...coverageIgnores],
  testEnvironment: 'node',
  coverageThreshold: {
    global: {
      branches: 86,
      functions: 75,
      lines: 86,
      statements: 86,
    },
  },
  preset: 'ts-jest',
};

The configuration currently uses the ts-jest preset. The project also involves a DynamoDB instance that should be tested and that's where multiple presets come into play. The current preset, ts-jest, should be used in combination with the @shelf/jest-dynamodb-preset (https://jestjs.io/docs/en/dynamodb). The problem is that the preset property in the config is of type String and doesn't support an array or an object.

I've read some similar questions like this one; Is it possible to use Jest with multiple presets at the same time?, but questions like these don't seem to have a definitive working solution on how to solve this problem.

Others suggest a solution in which a separate Jest config is created for every preset, but this is something I don't want and that probably will cause more problems in the future.

It would be ideal to have this single config file modified to allow multiple (here 2) presets, but how can this be achieved?

Upvotes: 18

Views: 5670

Answers (2)

Bertie92
Bertie92

Reputation: 707

This is specific to the marriage of ts-jest and jest-dynamodb, but what worked for me was to change the jest config like this:

"jest": {
    "preset": "@shelf/jest-dynamodb",
    "transform": {
      "^.+\\.tsx?$": [
        "ts-jest",
        {}
      ]
    },
    // ...
  }

Upvotes: 1

Kris White
Kris White

Reputation: 689

You can't actually use two presets but since the preset for shelf/jest-dynamodb is just setting other options in the jest setup, you can call them yourself. I was able to do this by just adding to my "jest" section of package.json:

"globalSetup": "./node_modules/@shelf/jest-dynamodb/setup.js",
"globalTeardown": "./node_modules/@shelf/jest-dynamodb/teardown.js",

This makes the same calls that the preset was doing, meaning you can leave the preset to ts-jest

Upvotes: 7

Related Questions