当我尝试运行笑话单元测试时遇到命名导出问题

问题描述 投票:0回答:1

我正在尝试编写单元测试用例,但是当我为特定文件运行命令 npm run test 时,我为我的应用程序添加的命名导出出现错误

Cannot find module '@decorators'
。还有一个名为导出
@entities
,它引发了同样的问题。下面是我在根文件夹中添加的笑话配置文件。为了清楚起见,我正在使用 Nestjs 项目。

module.exports = {
  moduleFileExtensions: ['js', 'json', 'ts'],
  rootDir: '.',
  testEnvironment: 'node',
  transform: {
    '^.+\\.(t|j)s$': 'ts-jest',
  },
  moduleNameMapper: {
    '^@entities/(.*)$': 'src/entities/$1',
    '^@decorators/(.*)$': 'src/utils/decorators/$1',
  },
};

帮我找到解决方案。在玩笑配置中也尝试了多种方法,但似乎没有任何效果。

更新 package.json 中的 jest 配置

"jest": {
    "moduleNameMapper": {
      "^src/(.*)$": "<rootDir>/$1",
      "^@decorators/(.*)$": "<rootDir>/utils/decorators/$1",
      "^entities/(.*)$": "<rootDir>/entities/$1"
    },
    "moduleFileExtensions": [
      "js",
      "json",
      "ts"
    ],
    "rootDir": "src",
    "testRegex": ".*\\.spec\\.ts$",
    "transform": {
      "^.+\\.(t|j)s$": "ts-jest"
    },
    "collectCoverageFrom": [
      "**/*.(t|j)s"
    ],
    "coverageDirectory": "../coverage",
    "testEnvironment": "node"
  }

详细错误

Test suite failed to run

    Cannot find module '@decorators' from 'modules/test2/entities/test2.entity.ts'

    Require stack:
      modules/test2/entities/test2.entity.ts
      modules/test1/entities/test1.entity.ts
      entities/index.ts
      modules/test-module/test.service.ts
      modules/test-module/test.service.spec.ts

      1 | import { ObjectType } from '@nestjs/graphql';
      2 | import { Entity } from 'typeorm';
    > 3 | import {
        | ^
      4 |   TimestampColumnOptional,
      5 |   StringColumnOptional,
      6 |   IntColumnOptional,
      at Resolver._throwModNotFoundError (../node_modules/jest-resolve/build/resolver.js:428:11)

我添加了一些在实体文件中使用的自定义装饰器。命名导出后,我将像下面的示例一样导入它。项目工作正常,但单元测试用例抛出了我提到的问题。

import {
  IntColumnOptional,
  StringColumnOptional,
  BooleanColumnOptional
} from '@decorators';
typescript unit-testing jestjs nestjs tsconfig
1个回答
0
投票

"^@decorators/(.*)$
@decorators
不匹配,因此 Jest 无法知道
@decorators
指的是文件方面的内容。更有可能的是,将
^@decorators$': 'src/utils/decorators'
添加到笑话配置中,一切都会按预期进行

© www.soinside.com 2019 - 2024. All rights reserved.