当我尝试运行jest单元测试时,

7vux5j2d  于 5个月前  发布在  Jest
关注(0)|答案(1)|浏览(107)

我试图编写单元测试用例,但当我运行命令npm run test的特定文件,我得到错误Cannot find module '@decorators'命名的出口我已经为我的应用程序添加.还有一个命名的出口@entities这是抛出相同的问题.下面是我的jest配置文件,我已经添加到根文件夹.我使用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',
  },
};

字符串
帮我找到解决方案。在jest配置中尝试了多种方法,但似乎都不起作用。
更新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';

o2gm4chl

o2gm4chl1#

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

相关问题