Nx Angular Monorepo 中 cypress 组件测试的代码覆盖率?

Rud*_*ler 3 components code-coverage angular cypress nrwl-nx

我已经设置了一个带有 Angular 应用程序和两个库的 NX monorepo:mylib-amylib-b. 每个库都有一个组件(TitleWidgetinmylib-aTitleWidgetBin mylib-b)。每个组件都有自己的一组赛普拉斯组件测试。我可以单独运行每个库的测试,但我正在努力弄清楚如何检测我的源代码并进一步获得两个组件的组合测试覆盖率报告。

您可以在此处找到示例应用程序以及有关如何运行它的说明:https://github.com/rtm-celum/angular-cypress-component-test-coverage

我遵循 cypress E2E 代码覆盖率指南(https://docs.cypress.io/guides/tooling/code-coverage#E2E-and-unit-code-coverage)并设法安装了该插件及其周围的所有内容。

我还尝试遵循https://nx.dev/packages/angular/generators/cypress-component-configuration并通过我的应用程序文件中的目标添加仪器设置( babel-loaderbabel-plugin-istanbul)作为附加 webpack 配置。cypress.config.tsproject.json

无论我尝试什么,当我执行 cypress 组件测试时,.nyc_output/out.json始终为空{}

But*_*hen 5

我也遇到了设置问题,但最终我找到了解决方案。

以下是所需的步骤:

  1. 安装更多依赖项:
    npm i @cypress/code-coverage @jsdevtools/coverage-istanbul-loader -D
    
    Run Code Online (Sandbox Code Playgroud)
  2. 将自定义 webpack 配置添加到我们的项目中
    import * as path from "path";
    
    export const CoverageWebpack = {
        module: {
            rules: [
                {
                    test: /\.(js|ts)$/,
                    loader: '@jsdevtools/coverage-istanbul-loader',
                    options: {esModules: true},
                    enforce: 'post',
                    include: [
                        path.join(__dirname, '../..', 'apps'),
                        path.join(__dirname, '../..', 'libs')
                    ],
                    exclude: [
                        /\.(cy|spec)\.ts$/,
                        /node_modules/
                    ]
                }
            ]
        }
    };
    
    Run Code Online (Sandbox Code Playgroud)
  3. 像这样修改 cypress.config.ts:
     import {nxComponentTestingPreset} from '@nx/angular/plugins/component-testing';
     import {defineConfig} from 'cypress';
     import {CoverageWebpack} from './coverage.webpack'
    
     const nxPreset = nxComponentTestingPreset(__filename);
    
     export default defineConfig({
       component: {
         ...nxPreset,
       devServer: {
         ...nxPreset.devServer,
         webpackConfig: CoverageWebpack,
       },
       setupNodeEvents(on, config) {
       // eslint-disable-next-line @typescript-eslint/no-var-requires
       require('@cypress/code-coverage/task')(on, config)
       // include any other plugin code...
    
           // It's IMPORTANT to return the config object
           // with any changed environment variables
           return config;
         },
       }
     });
    
    Run Code Online (Sandbox Code Playgroud)
  4. 将以下行添加到 component.ts (thx @Miguel)
    import '@cypress/code-coverage/support'
    
    Run Code Online (Sandbox Code Playgroud)

这是 mylib-a 的结果: 覆盖输出 html

不幸的是,cypress 命令也将被列出。也许可以通过更改coverage.webpack.ts中的包含或排除来解决这个问题。

我希望我没有忘记任何事情。(我克隆了您的项目并对其进行了修改。如果您为我创建一个分支,如果您愿意,我可以将我的更改推送到其中。)