12

问题描述:
我为一个打字稿类写了两个测试。这两个测试通过了,所以 jest 成功地检索了测试文件。然后我使用 --coverage 选项,但似乎 jest 没有在这里选择覆盖的文件。
这是我得到的输出:

api_jester    | PASS src/tests/repositories/user.test.ts
api_jester    |   User Repository
api_jester    |     ✓ it should return an empty array (18ms)
api_jester    |     ✓ should successfully create a user and return its data (7ms)
api_jester    | 
api_jester    | ----------|----------|----------|----------|----------|-------------------|
api_jester    | File      |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
api_jester    | ----------|----------|----------|----------|----------|-------------------|
api_jester    | All files |        0 |        0 |        0 |        0 |                   |
api_jester    | ----------|----------|----------|----------|----------|-------------------|
api_jester    | Test Suites: 1 passed, 1 total
api_jester    | Tests:       2 passed, 2 total
api_jester    | Snapshots:   0 total
api_jester    | Time:        3.208s
api_jester    | Ran all test suites.

我曾尝试使用 collectCoverageFrom 选项,但没有任何成功。我已经用在 github 上找到的一些简单示例进行了测试,这些示例可以正常工作,因此问题不在于我的环境。我猜我以某种方式错过了我的配置中的某些内容,但是我花了很多时间在这上面,我有点沮丧,所以也许一些新的外观会有所帮助..

项目架构:

config
|__ jest.config.js
|__ tsconfig.json
src
|__tests
|  |__repositories
|     |__user.test.ts
|__repositories
   |___ userRepository
        |__User.ts

Jest.config.js :

module.exports = {
  preset: "ts-jest",
  testEnvironment: "node",
  roots: ["../src/tests/"],
  transform: {
    "^.+\\.tsx?$": "ts-jest"
  },
  collectCoverageFrom: ["../src/"],
  moduleFileExtensions: ["ts", "js", "json"],
  coverageDirectory: "../coverage"
};

包.json

{
  "name": "theralog_api",
  "version": "1.0.0",
  "description": "",
  "main": "server.js",
  "scripts": {
    "build": "tsc",
    "prettier": "npx prettier --write src/**/*.ts --config ./config/.prettierrc",
    "eslint": "npx eslint --config ./config/.eslintrc ./src/**/**/*",
    "start:dev": "npx nodemon -L --config ./config/api.nodemon.json",
    "test:watch": "npx nodemon -L --config ./config/jester.nodemon.json",
    "test:coverage": "npx jest --config ./config/jest.config.js --coverage --colors --watch"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@types/compression": "^1.0.1",
    "@types/express": "^4.17.1",
    "@types/graphql-depth-limit": "^1.1.2",
    "@types/jest": "^24.0.23",
    "@types/node": "^12.7.12",
    "@typescript-eslint/eslint-plugin": "^2.5.0",
    "@typescript-eslint/parser": "^2.5.0",
    "apollo-server-testing": "2.9.7",
    "babel-jest": "^24.9.0",
    "eslint": "^6.5.1",
    "eslint-config-prettier": "^6.4.0",
    "graphql-depth-limit": "^1.1.0",
    "graphql-import": "^0.7.1",
    "graphql-import-node": "0.0.4",
    "jest": "^24.9.0",
    "nodemon": "^1.19.3",
    "prettier": "^1.18.2",
    "ts-jest": "^24.1.0",
    "ts-node": "^8.4.1",
    "tsconfig-paths": "^3.9.0",
    "typescript": "^3.7.2"
  },
  "dependencies": {
    "apollo-server-express": "^2.9.6",
    "compression": "^1.7.4",
    "cors": "^2.8.5",
    "dotenv": "^8.2.0",
    "express": "^4.17.1",
    "graphql": "^14.5.8",
    "http": "0.0.0",
    "lodash": "^4.17.15",
    "ncp": "^2.0.0",
    "pg": "^7.12.1",
    "winston": "3.2.1"
  }
}

jester.nodemon.json

{
  "watch": ["../src"],
  "ext": "ts",
  "exec": "npx jest --config ./config/jest.config.js --watchAll"
}
4

2 回答 2

6

您在 jest.config.js 中缺少一个设置,collectCoverage: true

module.exports = {
  preset: "ts-jest",
  testEnvironment: "node",
  roots: ["../src/tests/"],
  transform: {
    "^.+\\.tsx?$": "ts-jest"
  },
  collectCoverage: true,
  collectCoverageFrom: ["../src/"],
  moduleFileExtensions: ["ts", "js", "json"],
  coverageDirectory: "../coverage"
};

我还使用了更具描述性的 collectCoverageFrom:

collectCoverageFrom: [
    '<rootDir>/src/**/*.ts',
    '!<rootDir>/src/**/*.interface.ts',
    '!<rootDir>/src/**/*.mock.ts',
    '!<rootDir>/src/**/*.module.ts',
    '!<rootDir>/src/**/*.spec.ts',
    '!<rootDir>/src/**/*.test.ts',
    '!<rootDir>/src/**/*.d.ts'
],

通过这种方式,我排除了一些我不想计算覆盖率的文件,例如我的模块、模拟和测试。

我的完整文件包含原始的 Jest 初始化过程和其中的评论。

有关每个配置属性的详细说明,请访问:Jest 文档

module.exports = {
    // All imported modules in your tests should be mocked automatically
    // automock: false,

    // Stop running tests after the first failure
    // bail: false,

    // Respect "browser" field in package.json when resolving modules
    // browser: false,

    // The directory where Jest should store its cached dependency information
    // cacheDirectory: "C:\\Users\\sscott\\AppData\\Local\\Temp\\jest",

    // Automatically clear mock calls and instances between every test
    // clearMocks: false,

    // Indicates whether the coverage information should be collected while executing the test
    collectCoverage: true,

    // An array of glob patterns indicating a set of files for which coverage information should be collected
    collectCoverageFrom: [
        '<rootDir>/src/**/*.ts',
        '!<rootDir>/src/**/*.mock.ts',
        '!<rootDir>/src/**/*.module.ts',
        '!<rootDir>/src/**/*.spec.ts',
        '!<rootDir>/src/**/*.test.ts',
        '!<rootDir>/src/**/*.d.ts'
    ],
    // The directory where Jest should output its coverage files
    coverageDirectory: "<rootDir>/docs",

    // An array of regexp pattern strings used to skip coverage collection
    coveragePathIgnorePatterns: [
        "\\\\node_modules\\\\"
    ],

    // A list of reporter names that Jest uses when writing coverage reports
    coverageReporters: [
        "lcov",
        "clover",
        "text-summary"
    ],

    // An object that configures minimum threshold enforcement for coverage results
    // coverageThreshold: null,

    // Make calling deprecated APIs throw helpful error messages
    errorOnDeprecated: true,

    // Force coverage collection from ignored files usin a array of glob patterns
    // forceCoverageMatch: [],

    // A path to a module which exports an async function that is triggered once before all test suites
    // globalSetup: null,

    // A path to a module which exports an async function that is triggered once after all test suites
    // globalTeardown: null,

    // A set of global variables that need to be available in all test environments
    globals: {
        "ts-jest": {
            "diagnostics": false,
            "tsConfig": "tsconfig.json"
        }
    },

    // An array of directory names to be searched recursively up from the requiring module's location
    // moduleDirectories: [
    //   "node_modules"
    // ],

    // An array of file extensions your modules use
    moduleFileExtensions: [
        "ts",
        "tsx",
        "js"
    ],

    // A map from regular expressions to module names that allow to stub out resources with a single module
    // moduleNameMapper: {},

    // An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
    // modulePathIgnorePatterns: [],

    // Activates notifications for test results
    // notify: false,

    // An enum that specifies notification mode. Requires { notify: true }
    // notifyMode: "always",

    // A preset that is used as a base for Jest's configuration
    // preset: null,

    // Run tests from one or more projects
    // projects: null,

    // Use this configuration option to add custom reporters to Jest
    // reporters: undefined,

    // Automatically reset mock state between every test
    // resetMocks: false,

    // Reset the module registry before running each individual test
    // resetModules: false,

    // A path to a custom resolver
    // resolver: null,

    // Automatically restore mock state between every test
    // restoreMocks: false,

    // The root directory that Jest should scan for tests and modules within
    // rootDir: null,

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

    // Allows you to use a custom runner instead of Jest's default test runner
    // runner: "jest-runner",

    // The paths to modules that run some code to configure or set up the testing environment before each test
    // setupFiles: [],

    // The path to a module that runs some code to configure or set up the testing framework before each test
    // setupTestFrameworkScriptFile: null,

    // A list of paths to snapshot serializer modules Jest should use for snapshot testing
    // snapshotSerializers: [],

    // The test environment that will be used for testing
    testEnvironment: "node",

    // Options that will be passed to the testEnvironment
    // testEnvironmentOptions: {},

    // Adds a location field to test results
    // testLocationInResults: false,

    // The glob patterns Jest uses to detect test files
    testMatch: [
        "**/*.spec.ts"
    ],

    // An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
    // testPathIgnorePatterns: [
    //   "\\\\node_modules\\\\"
    // ],

    // The regexp pattern Jest uses to detect test files
    // testRegex: "",

    // This option allows the use of a custom results processor
    // testResultsProcessor: null,
    // "testResultsProcessor": "jest-jenkins-reporter",
    
    // This option allows use of a custom test runner
    // testRunner: "jasmine2",

    // This option sets the URL for the jsdom environment. It is reflected in properties such as location.href
    // testURL: "http://localhost",

    // Setting this value to "fake" allows the use of fake timers for functions such as "setTimeout"
    // timers: "real",

    // A map from regular expressions to paths to transformers
    transform: {
        "^.+\\.(ts|tsx)$": "ts-jest"
    },

    // An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
    // transformIgnorePatterns: [
    //   "\\\\node_modules\\\\"
    // ],

    // An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them
    // unmockedModulePathPatterns: undefined,

    // Indicates whether each individual test should be reported during the run
    verbose: false

    // An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode
    // watchPathIgnorePatterns: [],

    // Whether to use watchman for file crawling
    // watchman: true,
};
于 2019-11-18T16:50:12.513 回答
0

经过几页的大量研究后,这对我来说是为了获得覆盖率报告:

将下面的行放在脚本下:

"test:coverage": "set CI=true && react-scripts test --coverage",

package.json 图片

并且,在 package.json 文件中添加以下代码用于 jest 配置,如下所示:

 "jest": {
    "collectCoverageFrom": [
      "**/*.{js,jsx}",
      "!**/node_modules/**",
      "!**/coverage/**",
      "!**/serviceWorker.js",
      "!**/index.js"
    ],
    "coveragePathIgnorePatterns": [
      "/node_modules/",
      "package.json",
      "package-lock.json"
    ]
  }

package.json 文件中的笑话

然后运行

npm run test:coverage
于 2021-01-22T14:44:18.787 回答