开发者

Jest cannot find typescript module '../X.js' from 'src/tests/X.test.ts'

I've been trying to find a way to test my TypeScript project but with every try Jest or typescript have yelled at me.

This is my project directory
.
├── jest.config.js
├── package.json
├── src
│   ├── main.ts
│   └── tests
│       └── main.test.ts
└── tsconfig.json
jest.config.js
/** @type {import('ts-jest').JestConfigWithTsJest} */
export default {
  preset: 'ts-jest',
  testEnvironment: 'node',
};
package.json
{
  "type": "module",
  "scripts": {
    "test&开发者_StackOverflowquot;: "jest"
  },
  "devDependencies": {
    "@types/jest": "^29.2.4",
    "jest": "^29.3.1",
    "ts-jest": "^29.0.3"
  },
  "dependencies": {
    "chalk": "^5.1.2"
  }
}
tsconfig.json
{
  "compilerOptions": {
    "target": "ES2022",
    "module": "NodeNext",
    "moduleResolution": "NodeNext",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "rootDir": "./src",
    "outDir": "./dist",
    "strict": true,
    "skipLibCheck": true
  }
}

./src/main.ts

import chalk from "chalk";

function dumyFn(num: number, num2: number) {
  return num + num2;
}

export { dumyFn };

./src/tests/main.test.ts

import { dumyFn } from "../main.js"; // Problem is here
test("simple dummy test", () => {
  expect(dumyFn(2, 3)).toBe(5);
});

Whenever I try to run this test it's going to fail and the error is.

 FAIL  src/tests/main.test.ts
  ● Test suite failed to run

    Cannot find module '../main.js' from 'tests/main.test.ts'

    > 1 | import { dumyFn } from "../main.js"; // problem is here
        | ^
      2 | test("simple dummy test", () => {
      3 |   expect(dumyFn(2, 3)).toBe(5);
      4 | });

      at Resolver._throwModNotFoundError (../node_modules/jest-resolve/build/resolver.js:425:11)
      at Object.<anonymous> (tests/main.test.ts:1:1)

I Found out that if I change the first line of src/tests/main.test.ts something like below, this problem fades away but a new problem comes to me.

// import { dumyFn } from "../main.js"; // problem is here
import { dumyFn } from "../main";

TypeScript compiler yells at me :

Jest cannot find typescript module '../X.js' from 'src/tests/X.test.ts'

How can get rid of both of the problems?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜