Skip to content

When am I supposed to call compileComponents, and how am I getting away with not doing so?

The docs for compileComponents unhelpfully state only this:

Compile components with a templateUrl for the test’s NgModule. It is necessary to call this function as fetching urls is asynchronous.

However, this doesn’t explain in what circumstances is it “necessary” to call this function, nor what the consequences are of not doing so. The app I am currently working on has unit tests for components with templateUrls and those tests involve looking at the DOM using By.css, yet they seem to work fine even though we never call compileComponents anywhere in our codebase. Meanwhile, there are other posts on the internet, like https://github.com/angular/angular-cli/pull/4757, that suggest that calling compileComponents is not required.

In what circumstances should I call this method, and why?

Answer

In what circumstances should I call this method, and why?

If you’re using webpack (if configured properly), the build will compile the templateUrls into inline templates and styleUrls to styles. So there is no need to compileComponents because it’s just like you’re using template and styles even though you’re not.

If for example you’re using SystemJS (or you don’t have some other build step that does this pre-compilation/conversion), this doesn’t happen. Angular will need to make an XHR request to retrieve the external templates and external styles, and then compile. Here, you will need to compileComponents.

This is stated in the Angular v2 testing docs

WebPack developers need not call compileComponents because it inlines templates and css as part of the automated build process that precedes running the test.

As well as in the more recent docs of Angular v13 related to calling compileComponents:

Ignore this section if you only run tests with the CLI ng test command because the CLI compiles the application before running the tests.