最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

jestjs - How to configure Jest properly in a pnpm monorepo with TypeScript, React, and Vite? - Stack Overflow

matteradmin6PV0评论

In Hello.spec.tsx, Jest is unable to recognize the Test component. This component is located in the ui library within the /libs directory of the monorepo. I’ve tried importing it using the standard import syntax, but Jest is throwing an error indicating that it can’t resolve the module. Since Test is part of the shared ui library, I’m unsure if this issue is related to module resolution across packages in the monorepo or if there's a configuration issue with Jest not properly handling the path to the ui library.

pds/src/components/Hello.tsx

import { Test } from "@libs/ui"; // 'Test' component is from 'monorepo/libs/ui'
export default () => (
  <>
    <p>Hello Diego was here</p>
    <Test />
  </>
);

pds/src/components/Hello.spec.tsx

/**
 * @jest-environment jsdom
 */

// Component.test.js
import { render, screen } from '@testing-library/react'
import Component from './Hello';
import '@testing-library/jest-dom'


test('renders paragraph and Test component', () => {
  render(<Component />)

  // Check if the paragraph is rendered
  expect(screen.getByText(/Hello Diego was here/i)).toBeInTheDocument()
})

/ui/src/Test.tsx

export const Test: React.FC = () => <p>This is a Test Component</p>

Other test file that pass

/pds/src/add.ts

export const add = (a: number, b: number) => {
  return a + b;
}

/pds/src/add.spec.ts

import { add } from "./add";

describe("add function", () => {
  it("should add two number together", () => {
    const result = add(10, 5);
    expect(result).toBe(15);
  });
});

Steps to recreate this problem

  1. Install pnpm
  2. Create folder monorepo
  3. CD in monorepo and run command pnpm init
  4. Create file monorepo/pnpm-workspace.yaml and copy and paste the content I provided in this post
  5. Create two folders: apps and libs
  6. CD into apps and run command pnpm create vite@latest (Note: make sure you select typescript and react as the starting template)
  7. Similarly, cd into libs and run command pnpm create vite@latest (Note: make sure you select typescript and react as the starting template)
  8. Replace the contents of package.json, vite.config.ts, and tsconfig.json with the respective content I’ve provided in this post for the project in pds and ui.

Here's my project stucture

/monorepo
  ├── pnpm-workspace.yaml
  ├── package.json
  ├── jest.config.ts
  ├── tsconfig.build.json
  ├── tsconfig.json
  ├── /apps
  │    └── /pds
  │        ├── package.json
  │        ├── vite.config.ts
  │        └── tsconfig.json
  └── /libs
       └── /ui
           ├── tsconfig.json
           ├── vite.config.ts
           └── package.json

/monorepo/pnpm-workspace.yaml

packages:
  - 'apps/*'
  - 'libs/*'

/monorepo/package.json

{
  "name": "monorepo",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "pds": "pnpm --filter @apps/pds",
    "ui": "pnpm --filter @libs/ui",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@eslint/js": "^9.19.0",
    "@testing-library/jest-dom": "^6.6.3",
    "@types/jest": "^29.5.14",
    "eslint": "^9.20.0",
    "globals": "^15.14.0",
    "jest": "^29.7.0",
    "jest-environment-jsdom": "^29.7.0",
    "ts-jest": "^29.2.5",
    "ts-node": "^10.9.2",
    "typescript": "~5.7.2",
    "typescript-eslint": "^8.22.0",
    "vite": "^6.1.0"
  }
}

/monorepo/jest.config.ts

import { Config } from 'jest';

const config: Config = {
  // verbose: true,
  preset: "ts-jest",
  testEnvironment: "jsdom",
  transform: {
    "^.+\\.(ts|tsx)$": "ts-jest",
  },
  projects: [
    {
      displayName: 'pds',
      preset: 'ts-jest',
      testEnvironment: 'jsdom',
      testMatch: ['<rootDir>/apps/pds/src/**/*.spec.tsx', '<rootDir>/apps/pds/src/**/*.spec.ts'],
      transform: {
        '^.+\\.(ts|tsx)$': 'ts-jest'
      },
    }
  ],
};

module.exports = config;

/monorepo/tsconfig.build.json

{
  "compilerOptions": {
    "target": "ES2020",
    "useDefineForClassFields": true,
    "lib": ["ES2020", "DOM", "DOM.Iterable"],
    "module": "ESNext",
    "skipLibCheck": true,
    "allowSyntheticDefaultImports": true,
    "forceConsistentCasingInFileNames": true,
    "moduleResolution": "bundler",
    "jsx": "react-jsx",
    "strict": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noFallthroughCasesInSwitch": true,
    "noUncheckedSideEffectImports": true,
    "esModuleInterop": true
  }
}

/monorepo/tsconfig.json

{
  "compilerOptions": {
    "jsx": "react-jsx",
    "baseUrl": "./",
    "paths": {
      "@apps/pds/*": ["apps/pds/src/*"],
      "@libs/ui/*": ["libs/ui/src/*"]
    }
  },
  "files": [],
  "references": [
    {
      "path": "apps/pds"
    },
    {
      "path": "libs/ui"
    }
  ]
}

pds/package.json

{
  "name": "@apps/pds",
  "private": true,
  "version": "0.0.0",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "tsc -b && vite build",
    "lint": "eslint .",
    "preview": "vite preview",
    "test": "jest"
  },
  "dependencies": {
    "@libs/ui": "workspace:^",
    "react": "^19.0.0",
    "react-dom": "^19.0.0"
  },
  "devDependencies": {
    "@testing-library/dom": "^10.4.0",
    "@testing-library/jest-dom": "^6.6.3",
    "@testing-library/react": "^16.2.0",
    "@testing-library/user-event": "^14.6.1",
    "@types/react": "^19.0.8",
    "@types/react-dom": "^19.0.3",
    "@vitejs/plugin-react": "^4.3.4",
    "eslint-plugin-react-hooks": "^5.0.0",
    "eslint-plugin-react-refresh": "^0.4.18"
  }
}

/pds/vite.config.ts

import { defineConfig } from 'vite';
import { resolve } from 'path';
import react from '@vitejs/plugin-react';

// /config/
export default defineConfig({
  resolve: {
    alias: {
      '@': resolve(__dirname, 'src'),
    }
  },
  plugins: [react()],
})

/pds/tsconfig.json

{
  "extends": "../../tsconfig.build.json",
  "compilerOptions": {
    "composite": true,
    "allowImportingTsExtensions": true,
    "noEmit": true,
    "rootDir": "./src",
    "outDir": "./dist",
    "paths": {
      "@/*": ["./src/*"],
    }
  },
  "references": [
    { "path": "../../libs/ui" },
  ],
  "include": ["src/**/*"],
  "exclude": ["dist", "node_modules"],
}

/ui/tsconfig.json

{
  "extends": "../../tsconfig.build.json",
  "compilerOptions": {
    "composite": true,
    "rootDir": "./src",
    "outDir": "./dist",
    "paths": {
      "@/*": ["./src/*"],
    }
  },
  "include": ["src/**/*"],
  "exclude": ["dist", "node_modules"],
}

/ui/vite.config.ts

import { defineConfig } from 'vite';
import { resolve } from 'path';
import react from '@vitejs/plugin-react';
import dts from 'vite-plugin-dts';

// /config/
export default defineConfig({
  resolve: {
    alias: {
      '@': resolve(__dirname, 'src')
    }
  },
  build: {
    lib: {
      entry: resolve(__dirname, 'src/main.ts'),
      formats: ['es']
    },
    rollupOptions: {
      external: [
        'react',
        'react-dom'
      ],
      output: {
        globals: {
          react: 'React',
          'react-dom': 'ReactDom'
        },
        dir: 'dist',
      }
    }
  },

  plugins: [react(), dts()]
  // plugins: [react()],
})

/ui/package.json

{
  "name": "@libs/ui",
  "private": true,
  "version": "0.0.0",
  "type": "module",
  "main": "./dist/ui.cjs",
  "module": "./dist/ui.js",
  "types": "./dist/main.d.ts",
  "files": [
    "dist"
  ],
  "exports": {
    ".": {
      "types": "./dist/main.d.ts",
      "import": "./dist/ui.js",
      "require": "./dist/ui.cjs"
    }
  },
  "scripts": {
    "dev": "vite",
    "build": "tsc -b && vite build",
    "lint": "eslint .",
    "preview": "vite preview"
  },
  "peerDependencies": {
    "react": "^19.0.0",
    "react-dom": "^19.0.0"
  },
  "devDependencies": {
    "@types/react": "^19.0.8",
    "@types/react-dom": "^19.0.3",
    "@vitejs/plugin-react": "^4.3.4",
    "eslint-plugin-react-hooks": "^5.0.0",
    "eslint-plugin-react-refresh": "^0.4.18",
    "@types/node": "^22.13.1",
    "vite-plugin-dts": "^4.5.0"
  }
}

Articles related to this article

Post a comment

comment list (0)

  1. No comments so far