2

I have a project which works with React, TypeScript, Next.js and Jest using yarn.

If I try to test, it fails with the following error message.

FAIL src/components/Dashboard/Report.test.tsx

Test suite failed to run

    Your application tried to access src, but it isn't declared in your dependencies; this makes the require call ambiguous and unsound.

    Required package: src (via "src/components/CustomLink")
    Required by: /home/user/project/src/components/Dashboard/Report

I imported the CustomLink.tsx file in the Report.tsx file.

import { CustomLink } from 'src/components/CustomLink';

jest.config.js file is here.

module.exports = {
  roots: ['<rootDir>/src', '<rootDir>/pages', '<rootDir>/__tests__/pages'],
  globalSetup: '<rootDir>/__tests__/util/globalSetup.ts',
  setupFilesAfterEnv: ['<rootDir>/__tests__/util/setup.ts'],
  transform: {
    '\\.[jt]sx?$': 'babel-jest',
    '\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$':
      '<rootDir>/__tests__/util/fileMock.js',
    '\\.(gql|graphql)$': 'jest-transform-graphql',
  },
  moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
  clearMocks: true,
};

tsconfig.json file is here.

{
  "compilerOptions": {
    "baseUrl": ".",
    "target": "esnext",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
  },
  "exclude": ["node_modules"],
  "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".env"]
}

I figured this issue out by adding moduleNameMapper to the jest.config.js file.

  moduleNameMapper: {
    'src/(.*)': '<rootDir>/src/$1',
    '__tests__/(.*)': '<rootDir>/__tests__/$1',
  },

But what I have another issue is that jest can't find graphql generated files.

import { ReportType } from 'graphql/types.generated';
Test suite failed to run

    Qualified path resolution failed - none of the candidates can be found on the disk.

    Source path: /home/user/project/.yarn/cache/graphql-npm-15.5.0-65986c56be-789cdcb069.zip/node_modules/graphql/types.generated

I am using Graphql Apollo client so it generates the graphql types files automatically by yarn gql.

hotcakedev
  • 2,194
  • 1
  • 25
  • 47

0 Answers0