简体   繁体   English

Jest + nest.js,测试的绝对路径

[英]Jest + nest.js, absolute paths for tests

Here's my jest config inside of package.json :这是我在package.json jest配置:

"jest": {
  "moduleFileExtensions": [
    "js",
    "json",
    "ts"
  ],
  "moduleDirectories":["node_modules", "src"], // tried to solve the issue like that
  "rootDir": "src",
  "testRegex": ".spec.ts$",
  "transform": {
    "^.+\\.(t|j)s$": "ts-jest"
  },
  "coverageDirectory": "../coverage",
  "testEnvironment": "node"
}

AFAIK Nest doesn't add jest.config file, so package.json is my best bet. AFAIK Nest 不添加 jest.config 文件,所以 package.json 是我最好的选择。

But after doing this, my code still fails:但是这样做之后,我的代码仍然失败:

yarn run v1.22.5
$ jest
 FAIL  src/auth/auth.service.spec.ts
  ● Test suite failed to run

    Cannot find module 'src/auth/auth.service' from 'auth/auth.service.spec.ts'

      3 | import * as moment from 'moment';
      4 | import { RedisService } from '@custom/redis-client'; // this is in node_modules
    > 5 | import { AuthService } from 'src/auth/auth.service';
        | ^
      6 | import { ConfigService } from 'src/config/config.service';
      7 |
      8 | describe('AuthService', () => {

      at Resolver.resolveModule (../node_modules/jest-resolve/build/index.js:306:11)
      at Object.<anonymous> (auth/auth.service.spec.ts:5:1)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        3.486 s
Ran all test suites.
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

I also tried adding this to the jest config, as well as tsconfig:我还尝试将其添加到jest配置以及 tsconfig 中:

"moduleNameMapper": {
  "src/(.*)": "<rootDir>/$1",
  "tests/(.*)": "<rootDir>/__tests__/$1"
},

But with this code I get:但有了这个代码,我得到:

yarn run v1.22.5
$ jest
 FAIL  src/auth/auth.service.spec.ts
  ● Test suite failed to run

    Configuration error:
    
    Could not locate module ./src/redis/redis.health.indicator mapped as:
    /home/aironside/Documents/sygnum/dev-environment/api-layer/src/$1.
    
    Please check your configuration for these entries:
    {
      "moduleNameMapper": {
        "/src\/(.*)/": "/home/aironside/Documents/sygnum/dev-environment/api-layer/src/$1"
      },
      "resolver": undefined
    }

      at createNoMappedModuleFoundError (../node_modules/jest-resolve/build/index.js:551:17)
      at Object.<anonymous> (../node_modules/@sygnum/redis-client/index.ts:1:1)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        3.183 s
Ran all test suites.
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

What am I missing?我错过了什么?

My full tsconfig:我的完整 tsconfig:

{
  "compilerOptions": {
    "module": "commonjs",
    "declaration": true,
    "removeComments": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "allowSyntheticDefaultImports": true,
    "target": "es2017",
    "sourceMap": true,
    "outDir": "./dist",
    "baseUrl": "./",
    "incremental": true,
    "rootDir": "./",
  }
}

I use the ts-jest module for working with Jest in my Typescript projects.我使用 ts-jest 模块在我的 Typescript 项目中使用 Jest。 I use Jest for unit testing and E2E testing (at the moment) so I have different configuration files for each, with a common base module to not repeat settings.我使用 Jest 进行单元测试和 E2E 测试(目前),所以我有不同的配置文件,有一个通用的基本模块,不会重复设置。

My tests do not need to specify the src/ when importing files, just the normal paths under that.我的测试在导入文件时不需要指定 src/ ,只需指定其下的正常路径。 Also, this configuration has the plugins to support using the Typescript paths (@LIBRARY, @MODULE, etc.) in your source code.此外,此配置具有支持在源代码中使用 Typescript 路径(@LIBRARY、@MODULE 等)的插件。

jest-base.config.js jest-base.config.js

const tsconfig = require('./tsconfig.json');
const moduleNameMapper = require('tsconfig-paths-jest')(tsconfig);

module.exports = {
    moduleNameMapper,
    preset: 'ts-jest',
    testEnvironment: 'node',

    rootDir: './',

    collectCoverage: true,
    collectCoverageFrom: [
        '<rootDir>/**/*.ts',
        '!<rootDir>/**/*.interface.ts',
        '!<rootDir>/**/*.mock.ts',
        '!<rootDir>/**/*.module.ts',
        '!<rootDir>/**/__mock__/*',
        '!<rootDir>/src/main.ts'
    ],
    coverageProvider: 'v8',
    coverageReporters: [
        'clover',
        'json',
        'lcov',
        'text',
        'text-summary'
    ],
    resetModules: true,
    setupFiles: [
        'dotenv/config'
    ],
    // Add the community jest-extended matchers
    setupFilesAfterEnv: [
        'jest-extended'
    ],
    verbose: false
};

Then for unit tests, I use the following jest.config.js, with the package.json script option jest --watchAll --config ./jest.config.js然后对于单元测试,我使用以下 jest.config.js,以及 package.json 脚本选项jest --watchAll --config ./jest.config.js

jest.config.js开玩笑的配置文件

const JestBaseConfiguration = require('./jest-base.config');

module.exports = Object.assign(JestBaseConfiguration, {

    // A list of paths to directories that Jest should use to search for files in
    roots: [
        '<rootDir>/src',
    ],

    coverageDirectory: '<rootDir>/docs/coverage',
    coverageThreshold: {
        global: {
            branches: 80,
            functions: 50,
            lines: 50,
            statements: 50
        }
    },
    testTimeout: 30000    // Set in each config in case different values are needed
});

For End to End tests, I use the following jest-e2e.config.js, with the package.json script option jest --watchAll --config ./jest-e2e.config.js对于端到端测试,我使用以下 jest-e2e.config.js,以及 package.json 脚本选项jest --watchAll --config ./jest-e2e.config.js

jest-e2e.config.js jest-e2e.config.js

const JestBaseConfiguration = require('./jest-base.config');

module.exports = Object.assign(JestBaseConfiguration, {
    moduleFileExtensions: ['js', 'json', 'ts'],
    testRegex: '.e2e-spec.ts$',
    transform: {
        '^.+\\.(t|j)s$': 'ts-jest'
    },

    // A list of paths to directories that Jest should use to search for files in
    roots: [
        '<rootDir>/test'
    ],

    coverageDirectory: '<rootDir>/docs/e2e-coverage',
    coverageThreshold: {
        global: {
            branches: 5,
            functions: 5,
            lines: 5,
            statements: 5
        }
    },
    testTimeout: 30000    // Set in each file in case different values are needed
});

I had the same issue with absolute paths.我对绝对路径有同样的问题。 Instead of using:而不是使用:

  • "src/auth/auth.service"

I had to use我不得不使用

  • "../auth/auth.service"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM