Search code examples
reactjsjestjsmonorepo

Jest TypeError: Cannot read properties of undefined (reading 'html') at new JSDOMEnvironment


I've setup a monorepo with Node.js and React.

Trying to configure jest to run test suites the api Node works fine but I got the following error on the client side:

 FAIL client/src/App.test.tsx
  ● Test suite failed to run

    TypeError: Cannot read properties of undefined (reading 'html')

      at new JSDOMEnvironment (../node_modules/jest-environment-jsdom/build/index.js:72:44)

This is root jest.config.ts:

import type { Config } from '@jest/types';

const config: Config.InitialOptions = {
  globals: {
    'ts-jest': {
      tsconfig: 'tsconfig.json',
    },
  },
  roots: ['<rootDir>/server/src/tests', '<rootDir>/client/src/'],
  transform: {
    '^.+\\.(ts|tsx)$': 'ts-jest',
  },
  testMatch: ['**/src/**/*.test.ts', '**/src/**/*.test.tsx'],
  setupFilesAfterEnv: ['<rootDir>/client/src/setupTests.ts'],
  moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
  collectCoverage: true,
  coveragePathIgnorePatterns: ['(test/.*.mock).(jsx?|tsx?)$'],
  moduleNameMapper: {
    '\\.(css|scss|sass)$': 'identity-obj-proxy',
  },
  verbose: true,
  projects: [
    '<rootDir>/server/jest.config.ts',
    '<rootDir>/client/jest.config.ts',
  ],
  coverageDirectory: '<rootDir>/coverage/',
};

export default config;

The client jest.config.ts

import type { Config } from '@jest/types';

const config: Config.InitialOptions = {
  displayName: 'client',
  preset: 'ts-jest',
  testEnvironment: 'jsdom',
};

export default config;

And the script that fires jest in package.json scripts:

 "test:ci": "jest",

It seems that is not running react testing library.

However if I run the client test directly like so it works:

"test:client": "yarn workspace @mern-monorepo/client test",

What am I doing wrong ?


Solution

  • Well, after digging quite a bit I finally got the solution.

    This are the steps to follow:

    1. yarn workspace @mern-monorepo/client add --dev jest-environment-jsdom
    2. yarn workspace @mern-monorepo/client add --dev identity-obj-proxy

    Then I added to the client jest.config.ts file:

    import type { Config } from '@jest/types';
    
    const config: Config.InitialOptions = {
      displayName: 'client',
      preset: 'ts-jest',
      testEnvironment: 'jsdom',
      transformIgnorePatterns: ['\\.(css|scss|sass)$'],
      moduleNameMapper: {
        '\\.(css|scss|sass)$': 'identity-obj-proxy',
      },
      setupFilesAfterEnv: ['<rootDir>/src/setupTests.ts'],
    };
    
    export default config;