如何使用 angular-cli 只执行一个测试规范

How to execute only one test spec with angular-cli

我有 Angular2 个使用 Angular-CLI (beta 20) 构建的项目。

有没有办法 运行 仅针对一个选定的规范文件进行测试?

我曾经有一个基于 Angular2 快速入门的项目,我可以手动将规范添加到 jasmine 文件中。但我不知道如何在 karma 测试之外设置它,或者如何使用 Angular-CLI 构建将 karma 测试限制为特定文件。

您的每个 .spec.ts 文件都将其所有测试分组在 describe 块中,如下所示:

describe('SomeComponent', () => {...}

通过在 describe 函数名称前加上 f:

前缀,您可以轻松地 运行 这一个块

fdescribe('SomeComponent', () => {...}

如果你有这样的功能,其他describe块将不会运行。 顺便提一句。你可以用 it => fit 做类似的事情,还有一个 "blacklist" 版本 - x。所以:

  • fdescribefit 导致 只有 函数标记为 运行
  • xdescribexit 会导致 所有但 函数以这种方式标记为 运行

我用 g运行t 自己解决了这个问题。我在下面有 g运行t 脚本。该脚本所做的是将特定测试的命令行参数设为 运行 并创建 test.ts 的副本并将此特定测试名称放在那里。

要运行这个,首先安装g运行t-cli使用:

npm install -g grunt-cli

将以下 g运行t 依赖项放入 package.json:

"grunt": "^1.0.1",
"grunt-contrib-clean": "^1.0.0",
"grunt-contrib-copy": "^1.0.0",
"grunt-exec": "^2.0.0",
"grunt-string-replace": "^1.3.1"

为了运行,它将下面的 g运行t 文件保存为根文件夹中的 Gruntfile.js。然后从命令行 运行 为:

grunt --target=app.component

这将 运行 app.component.spec.ts。

G运行t文件如下:

/*
This gruntfile is used to run a specific test in watch mode. Example: To run app.component.spec.ts , the Command is: 
grunt --target=app.component
Do not specific .spec.ts. If no target is specified it will run all tests.
*/
module.exports = function(grunt) {
var target = grunt.option('target') || '';
  // Project configuration.
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    clean: ['temp.conf.js','src/temp-test.ts'],
    copy: {
      main: {
        files: [
             {expand: false, cwd: '.', src: ['karma.conf.js'], dest: 'temp.conf.js'},
             {expand: false, cwd: '.', src: ['src/test.ts'], dest: 'src/temp-test.ts'}
             ],
      }
    },
    'string-replace': {
          dist: {
            files: {
              'temp.conf.js': 'temp.conf.js',
              'src/temp-test.ts': 'src/temp-test.ts'
            },
            options: {
              replacements: [{
                pattern: /test.ts/ig,
                replacement: 'temp-test.ts'
              },
              {
                pattern: /const context =.*/ig,
                replacement: 'const context = require.context(\'./\', true, /'+target+'\\.spec\\.ts$/);'
              }]
            }
        }
    },
    'exec': {
        sleep: {
          //The sleep command is needed here, else webpack compile fails since it seems like the files in the previous step were touched too recently
          command: 'ping 127.0.0.1 -n 4 > nul',
          stdout: true,
          stderr: true
        },
        ng_test: {
          command: 'ng test --config=temp.conf.js',
          stdout: true,
          stderr: true
        }
    }
  });

  // Load the plugin that provides the "uglify" task.
    grunt.loadNpmTasks('grunt-contrib-clean');
    grunt.loadNpmTasks('grunt-contrib-copy');
    grunt.loadNpmTasks('grunt-string-replace');
    grunt.loadNpmTasks('grunt-exec');
  // Default task(s).
  grunt.registerTask('default', ['clean','copy','string-replace','exec']);

};

src 文件夹中配置 test.ts 文件:

const context = require.context('./', true, /\.spec\.ts$/);

/\.spec\.ts$/替换为您要测试的文件名。例如:/app.component\.spec\.ts$/

这将 运行 仅测试 app.component.spec.ts

如果您希望能够控制从命令行选择哪些文件,我设法做到了 Angular 7.

总之,您需要安装@angular-devkit/build-angular:browser,然后创建一个自定义的webpack 插件来传递测试文件正则表达式。例如:

angular.json - 从 @angular-devkit/build-angular:browser 更改测试生成器并设置自定义配置文件:

...

        "test": {
          "builder": "@angular-builders/custom-webpack:browser",
          "options": {
            "customWebpackConfig": {
              "path": "./extra-webpack.config.js"
            },
...

extra-webpack.config.js - 创建一个从命令行读取正则表达式的 webpack 配置:

const webpack = require('webpack');
const FILTER = process.env.KARMA_FILTER;
let KARMA_SPEC_FILTER = '/.spec.ts$/';
if (FILTER) {
  KARMA_SPEC_FILTER = `/${FILTER}.spec.ts$/`;
}
module.exports = {
  plugins: [new webpack.DefinePlugin({KARMA_SPEC_FILTER})]
}

test.ts - 编辑规范

...
// Then we find all the tests.
declare const KARMA_CONTEXT_SPEC: any;
const context = require.context('./', true, KARMA_CONTEXT_SPEC);

然后使用如下覆盖默认值:

KARMA_FILTER='somefile-.*\.spec\.ts$' npm run test

我记录了 backstory here,提前为类型和错误链接道歉。感谢@Aish-Anu 的上述回答,为我指明了正确的方向。

这在 Angular 7 中对我有用。它基于 ng 命令的 --main 选项。我不确定此选项是否未记录并且可能会更改,但它对我有用。我在脚本部分的 package.json 文件中放了一行。在 ng test 命令中使用 --main 选项,我指定了我要执行的 .spec.ts 文件的路径。例如

"test 1": "ng test --main E:/WebRxAngularClient/src/app/test/shared/my-date-utils.spec.ts",

您可以 运行 脚本,就像 运行 任何此类脚本一样。我通过单击 npm 部分中的 "test 1" 在 Webstorm 中 运行 它。

您可以使用 Angular CLIng 命令)仅测试特定文件,如下所示:

ng test --main ./path/to/test.ts

更多文档位于 https://angular.io/cli/test

请注意,虽然这适用于独立库文件,但不适用于 angular components/services/etc。这是因为 angular 文件依赖于其他文件(即 Angular 7 中的 src/test.ts)。可悲的是 --main 标志不接受多个参数。

为像我这样在 Angular 中寻找 运行 单个规范并找到此 SO 的人添加此内容。

根据最新的 Angular 文档(撰写本文时为 v9.0.6),ng test 命令有一个 --include 选项,您可以在其中指定 [=12] 的目录=] 个文件或一个 .spec.(ts|tsx) 文件本身。

https://angular.io/cli/test

只需在 src 文件夹内的 test.ts 文件中进行小改动:

const context = require.context('./', true, /test-example\.spec\.ts$/);

这里,test-example就是我们需要运行

的确切文件名

同理,如果只需要测试服务文件可以将文件名替换成"/test-example.service"

这在任何情况下都对我有用:

ng test --include='**/dealer.service.spec.ts'

但是,我通常会收到“TypeError:无法读取 属性 'ngModule' of null”:

ng test --main src/app/services/dealer.service.spec.ts

@angular/cli10.0.4

的版本

在 bash 终端中,我喜欢使用双破折号。使用 VS Code,您可以在资源管理器或打开的选项卡上右键单击规范文件。然后select'Copy Relative Path'。 运行 下面的命令从剪贴板粘贴相对路径。

npm t -- --include relative/path/to/file.spec.ts

双破折号表示 npm t 的命令选项结束,并将之后的任何内容传递给指向 ng t 的下一个命令。它不需要任何修改,并且可以快速提供所需的结果。

使用--include

它适用于 --include

ng test --include src/app/path-to-component/path-component.component.spec.ts

我尝试了 --main 但它显示了所有失败结果,而事实并非如此。我认为 --main 将更改主 test.ts 文件。

一个简单的方法是用 f[=16= 启动 describe 和所有 it ].

fdescribe('testecomponente', () => {
  fit('should create', () => {
    //your code 
  }
  
}
  

从 angular-cli 你可以 运行 这个命令,测试将只包含你想要的规范文件。

ng test --includes path of spec file

如果你在一个使用 monorepo 架构的项目中工作,那么你必须在命令行中的脚本后面写上项目的名称。 例如:

ng test MyProject1Name -- --include='myComponent.component.spec.ts'