Jest cannot find module in workspace
Asked Answered
V

0

9

I have an NPM project structured in workspaces:

proj/
+-node_modules/
+-packages/
  +-pkg1/
    +-src/
      |-c1.ts
      |-c1.test.ts
    |-package.json
    |-jest.config.js
  +-pkg2/
    +-src/
      |-c2.ts
    |-package.json
+-apps/
|-package.json

The project's package.json:

{
  "name": "proj",
  "scripts": {
    ...
    "test:pkg1": "npm test -w packages/pkg1",
  },
  "workspaces": [
    "packages/*",
    "apps/*"
  ]
}

The package.json inside pkg1:

{
  "name": "@proj/pkg1",
  "scripts": {
    ...
    "test": "jest --config=jest.config.js",
  },
  "devDependencies": {
    "@types/pegjs": "0.10.3",
    "@types/jest": "29.1.1",
    "ts-loader": "9.3.1",
    "typescript": "4.8.3",
    "webpack": "5.74.0",
    "webpack-cli": "4.10.0",
    "jest": "29.1.2",
    "ts-jest": "29.0.3"
  },
  "dependencies": {
    "@proj/pkg2": "1.0.0"
  }
}

The test file c1.test.ts is:

import { Component1 } from "@proj/pkg2";

describe("some tests", () => {
    test("a test case", () => {
        // Arrange ...
        // Act ...
        // Assert ...
    });
});

The problem

When, from the project's root, I run: npm run test:pkg1, I get:

    > 1 | import { Component1 } from "@proj/pkg2";
        | ^
      3 | describe("some tests", () => {
      4 | test("a test case", () => {
      5 | // Arrange

      at Resolver._throwModNotFoundError (../../node_modules/jest-resolve/build/resolver.js:487:11)

Jest cannot find "@proj/pkg2". It makes sense as it cannot understand workspaces and Jest compiles all files before running the tests. How to solve this?

Viridescent answered 10/12, 2022 at 9:56 Comment(1)
Did your problem got resolved?Foxed

© 2022 - 2024 — McMap. All rights reserved.