'How can I execute ng test for all components of sub modul of Angular app

I have my angular app, declared like this:

app.module.ts

export class AppModule {}

for which I can run tests with ng test MyApp

Within this app, I have multiple modules, declared like this:

my-one.module.ts / my-other.module.ts

export class MyOneModule {}

export class MyOtherModule {}

These are imported in AppModule.

How can I do something like ng test MyOneModule / ng test MyOtherModule, with which I'd like to run just the tests of all components in that very "sub module" instead of all tests in the app?

I couldn't find information in the official docu or here in StackOverflow. Is it possible at all?



Solution 1:[1]

I ended up using this workaround:

In test.ts I change the path:

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

to

const context: any = require.context('./app/modules/my-one-module', true, /\.spec\.ts$/);

or

const context: any = require.context('./app/modules/my-other-module', true, /\.spec\.ts$/);

This causes ng test to just execute the tests in the defined directory (and its sub directories).

Not ideal, as I don't like to make changes to checked-in files, that are not meant to be committed, but it does the job.

Solution 2:[2]

You can test each module seperately without the need for any code changes.

Dublicate test.ts and tsconfig.spec.json files for moduleone and rename like following;

test.moduleone.ts

tsconfig.moduleone.spec.json

find and change test.ts to test.moduleone.ts in tsconfig.moduleone.spec.json

"files": [
   "test.moduleone.ts"
]

find and change path as moduleone path in test.moduleone.ts;

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

run tests for moduleone like this;

ng test --main src/test.moduleone.ts --ts-config src/tsconfig.moduleone.spec.json

You can add script for each module to scripts section in package.json

"scripts":{
   "moduleone_tests":"ng test --main src/test.moduleone.ts --ts-config src/tsconfig.moduleone.spec.json"
}

so you can test each module with a simple command like

npm run moduleone_tests

Solution 3:[3]

You can find some resources online, such as this one, that explains how to grep files to run only them.

I also remember a coworker running his tests from intelliJ for a single file, and there was a command line argument, but I don't recall it at all.

Finally, you can also use fdescribe/xdescribe and fit/xit on the tests to run those ones only.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jasie
Solution 2
Solution 3