jest.config.js中的`moduleNameMapper`设置在CircleCI上无效。

37

我已经使用ts-jest在我的TypeScript React应用程序中进行了测试,就像下面这样。

import * as React from "react";
import * as renderer from "react-test-renderer";

import { ChartTitle } from "Components/chart_title";

describe("Component: ChartTitle", () => {
  it("will be rendered with no error", () => {
    const chartTitle = "My Chart 1";
    renderer.create(<ChartTitle title={chartTitle} />);
  });
});

这在我的本地环境中已经通过了,但在CircleCI上失败了。

 FAIL  __tests__/components/chart_title.tsx
  ● Test suite failed to run

    TypeScript diagnostics (customize using `[jest-config].globals.ts-jest.diagnostics` option):
    __tests__/components/chart_title.tsx:4:28 - error TS2307: Cannot find module 'Components/chart_title'.

    4 import { ChartTitle } from "Components/chart_title";                              
                                 ~~~~~~~~~~~~~~~~~~~~~~~~

这个 Components/ 是通过 moduleNameMapper 别名表达式进行的,我认为它只在 CircleCI 中不起作用。

jest --showConfig 选项告诉我本地环境和 CI 环境没有区别。

我的设置有什么问题吗?

app/frontend/jest.config.js

module.exports = {
  globals: {
    "ts-jest": {
      tsConfig: "tsconfig.json",
      diagnostics: true
    },
    NODE_ENV: "test"
  },
  moduleNameMapper: {
    "^Components/(.+)$": "<rootDir>/src/components/$1"
  },
  moduleDirectories: ["node_modules", 'src'],
  moduleFileExtensions: ["ts", "tsx", "js", "jsx", "json"],
  transform: {
    "^.+\\.tsx?$": "ts-jest"
  },
  verbose: true
};

应用程序/前端/tsconfig.json

{
  "compilerOptions": {
    "baseUrl": "src",
    "outDir": "dist",
    "allowJs": true,
    "checkJs": true,
    "moduleResolution": "node",
    "sourceMap": true,
    "noImplicitAny": true,
    "target": "esnext",
    "module": "commonjs",
    "lib": ["es6", "dom"],
    "jsx": "react",
    "strict": false,
    "removeComments": true,
    "types": ["jest"]
  },
  "typeRoots": ["node_modules/@types"],
  "paths": {
    "Components/*": ["src/components/*"]
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "__tests__"]
}

应用程序/前端/包.json

{
  "scripts": {
    "build": "webpack --mode development --watch",
    "build-production": "node_modules/.bin/webpack --mode production",
    "test": "jest",
    "lint": "npx eslint src/**/* __tests__/**/* --ext \".ts, .tsx\"",
  },
}

应用程序/.circleci/.config.yml

version: 2
jobs:
  build:
    ...
    steps:
      - run:
        name: run tests for frontend
        command: npm test -- -u
        working_directory: frontend
2个回答

45

tsconfig-paths-jest 在 Jest 23 以上版本中无法使用。对于当前的 Jest 26 版本,我通过以下方式让它可以工作:https://kulshekhar.github.io/ts-jest/docs/getting-started/paths-mapping/

jest.config.js

const { pathsToModuleNameMapper } = require('ts-jest');
const { compilerOptions } = require('./tsconfig');

module.exports = {
  preset: 'ts-jest',
  testEnvironment: 'node',
  moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths, { prefix: '<rootDir>/src/' } )
};

tsconfig.json中的“compilerOptions”

 "baseUrl": "./src",
 "paths": {            
  "@models/*": [ "./models/*" ],
  "@inputs/*": [ "./inputs/*" ],
  "@tests/*": [ "./__tests__/*" ],
  "@resolvers/*": [ "./resolvers/*" ],
  "@seeds/*": [ "./seeds/*" ],
  "@index": [ "./index.ts" ],
  "@ormconfig":[ "../ormconfig.ts" ]
  },

1
谢谢!这应该是正确的答案! - Carlo Corradini
1
在网上搜寻后,这是我找到的最佳解决方案。干得好,谢谢。 - TheoNeUpKID
1
我自己漏掉了 { prefix: '<rootDir>/src/' } 这一部分。谢谢! - derpedy-doo
2
更新的链接:https://kulshekhar.github.io/ts-jest/docs/getting-started/paths-mapping - blwinters
1
非常感谢这个。我查阅了许多Stack Overflow的帖子、博客等,但没有一个完整的解决方案 - pathsToModuleNameMapper的第二个参数,带有前缀的选项对象,正是我所缺少的。非常感谢。 - Mozgor

7

我终于找到解决方法了。

根据这个问题,我使用了tsconfig-pathstsconfig-paths-jest

所以我的设置文件如下所示。

tsconfig.json

{
  "compilerOptions": {
    "baseUrl": ".",
    "outDir": "dist/",
    "allowJs": true,
    "checkJs": true,
    "moduleResolution": "node",
    "sourceMap": true,
    "noImplicitAny": true,
    "target": "es6",
    "module": "commonjs",
    "lib": ["es5", "es6", "dom"],
    "jsx": "react",
    "strict": false,
    "removeComments": true,
    "types": ["node", "jest"],
    "paths": {
      "Components/*": ["src/components/*"]
    }
  },
  "typeRoots": ["node_modules/@types"],
  "include": ["src/**/*"],
  "exclude": ["node_modules", "__tests__"]
}

jest.config.js

/* eslint-disable import/order */
/* eslint-disable @typescript-eslint/no-var-requires */
const tsconfig = require("./tsconfig.json");
const moduleNameMapper = require("tsconfig-paths-jest")(tsconfig);

module.exports = {
  globals: {
    "ts-jest": {
      tsConfig: "tsconfig.json",
      diagnostics: true
    },
    NODE_ENV: "test"
  },
  setupFilesAfterEnv: [`${__dirname}/src/setupTests.ts`],
  moduleDirectories: ["node_modules", 'src'],
  moduleFileExtensions: ["ts", "tsx", "js", "jsx", "json"],
  transform: {
    "^.+\\.tsx?$": "ts-jest"
  },
  verbose: true,
  moduleNameMapper
};

我的测试在CircleCI上运行良好,但我仍然不知道为什么这些测试之前在本地可以运行。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接