program tip

angular-cli로 하나의 테스트 사양 만 실행하는 방법

radiobox 2020. 9. 23. 07:30
반응형

angular-cli로 하나의 테스트 사양 만 실행하는 방법


Angular-CLI (베타 20)로 Angular2 프로젝트 빌드가 있습니다.

선택한 하나의 사양 파일에 대해서만 테스트를 실행하는 방법이 있습니까?

저는 Angular2 빠른 시작을 기반으로 한 프로젝트를 가지고 있었고, 수동으로 jasmine 파일에 사양을 추가 할 수있었습니다. 그러나 나는 이것을 카르마 테스트 밖에서 설정하는 방법이나 Angular-CLI 빌드를 사용하여 카르마 테스트를 특정 파일로 제한하는 방법을 모릅니다.


.spec.ts파일에는 describe다음과 같은 블록으로 그룹화 된 모든 테스트가 있습니다 .

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

describe함수 이름 앞에 다음을 붙이면이 단일 블록 만 쉽게 실행할 수 있습니다 f.

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

이러한 기능이 있으면 다른 describe블록이 실행 되지 않습니다 . Btw. it=>로 비슷한 일을 할 수 fit있으며 "블랙리스트"버전도 x있습니다. 그래서:

  • fdescribefit원인 에만 실행하려면이 방법을 표시 기능을
  • xdescribexit원인 을 모두하지만, 기능을 실행하려면이 방법을 표시

폴더 test.ts내 파일 구성 src:

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

/\.spec\.ts$/테스트 할 파일 이름으로 바꿉니다 . 예를 들면 :/app.component\.spec\.ts$/

에 대한 테스트 만 실행됩니다 app.component.spec.ts.


다음과 같이 Angular CLI ( ng명령)를 사용하여 특정 파일 만 테스트 할 수 있습니다 .

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

추가 문서는 https://angular.io/cli/test에 있습니다.

이것은 독립 실행 형 라이브러리 파일에 대해서는 작동하지만 각도 구성 요소 / 서비스 등에 대해서는 작동하지 않습니다. 앵귤러 파일은 다른 파일 (즉 src/test.ts, Angular 7)에 종속되기 때문 입니다. 슬프게도 --main플래그는 여러 인수를 사용하지 않습니다.


명령 줄에서 선택되는 파일을 제어 할 수 있도록하려면 Angular 7에서이 작업을 수행했습니다.

요약하면, @angular-devkit/build-angular:browser테스트 파일 정규식을 통과하기 위해 사용자 지정 웹팩 플러그인을 설치 하고 생성 해야합니다 . 예를 들면 :

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- 명령 줄에서 정규식을 읽는 웹팩 구성을 만듭니다.

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);

Then use as follows to override the default:

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

I documented the backstory here, apologies in advance for types and mis-links. Credit to the answer above by @Aish-Anu for pointing me in the right direction.


This is working for me in Angular 7. It is based on the --main option of the ng command. I am not sure if this option is undocumented and possibly subject to change, but it works for me. I put a line in my package.json file in scripts section. There using the --main option of with the ng test command, I specify the path to the .spec.ts file I want to execute. For example

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

You can run the script as you run any such script. I run it in Webstorm by clicking on "test 1" in the npm section.


I solved this problem for myself using grunt. I have the grunt script below. What the script does is takes the command line parameter of the specific test to run and creates a copy of test.ts and puts this specific test name in there.

To run this, first install grunt-cli using:

npm install -g grunt-cli

Put the below grunt dependencies in your 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"

To run it save the below grunt file as Gruntfile.js in your root folder. Then from command line run it as:

grunt --target=app.component

This will run app.component.spec.ts.

Grunt file is as below:

/*
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']);

};

Every spec.ts file have all its tests grouped in describe block:

By default it's like:

describe('Component', () => { }

If you want to run a particular test cases:

fdescribe('Component', () => { }

To Ignore a file you can use 'x':

xdescribe('Component', () => { }

More Details:

xdescribe will eXclude those specs from execution.

fdescribe will first execute those specs. if you have both the fdescribe specs will be executed and reset is ignored

참고URL : https://stackoverflow.com/questions/40683673/how-to-execute-only-one-test-spec-with-angular-cli

반응형