Angular supports the setup of unit testing via it’s build-in TestBed. This class can be used to configure the environment the unit test runs in, including the available modules:
In the setup above, AppModule is imported into this test. AppModule is the root module of the whole application and hence provides every module used in the whole application. Because of this, no other modules have to be imported.
However, this has two huge downsides:
- The test will run slower because potentially unnecessary modules are loaded. In a very small application, I measured a 10% performance loss. I assume that for bigger applications, this will be much more.
- The understanding of what the test really covers is lost. Simply using everything in the application doesn’t force the developer to think about why this one component that should have nothing to do with the test has to be imported.
Hence, the better way is to import only the needed modules.
When doing test driven development (TDD), it should be fairly easy to know what to import because the tests are written before the real implementation. Hence, both the test class as well as the implementing class are developed together and with the same understanding of how things should work. Adding tests (a long time) after having coded the implementation raises questions such as “How do you know which components to import when unit testing?”.
TL;DR
Don’t import AppModule in your tests. Instead, import only needed modules.