When you generate something (component, service, pipe, etc) with the Angular CLI it also creates an associated spec file for testing that file. By default the main code file is named [name you provided].[type of file].ts and the spec file is named [name your provided].[type of file].spec.ts. So if you follow the Angular naming conventions all your component test files end in “.component.spec.ts” and all your service test files end in “.service.spec.ts”. This is good because we can use this pattern to run only a certain set of tests.
If you examine your angular.json file there will be a “test” property somewhere in the structure of your main angular project. There are two properties we are concerned with “main” which by default points to “src/test.ts” and “tsConfig” which points to “src/tsconfig.spec.json”. So when we use the command “ng test” it will by default use the settings assigned to “test” in the angular.json file. We would like to override those, but first lets understand what test.ts and tsconfig.spec.json are actually doing.
The test.ts file is the file that Karma uses to setup the test environment for Angular and load all the spec files. The default looks like this:
The tsconfig.spec.json file is used to by the typescript compiler to specify which files to load and compile. The default looks like this:
Creating an alternative test setup for service tests.
If you wanted to run only your service tests I suggest you do the following: 1) Create a new file in the src directory called test-services.ts and paste in:
2) Create a new file in the src directory called tsconfig.services.spec.json and paste in:
Normally when you run your tests using “ng test” on the command line it will use the default test.ts and tsconfig.spec.ts files. Instead now you will pass two additional flags to the ng test command.
By creating seperate test-[type].ts and and tsconfig.[type].spec.ts files we can easily run the tests we would like instead of all the tests in the suite. You can also use the “exclude” property if you wanted to run all your service, pipe, etc. tests, but not your component tests.
If you go down the route of running all the non-component tests the regular expression to filter the component tests out is: