Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 758
Mark Amery Avatar asked Apr 25 '17 10:04

Mark Amery


People also ask

Do I need compileComponents?

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.

What is compileComponents?

compileComponents() method in Angular test. 1. Angular TestBed configures and initializes environment for unit testing. The compileComponents() is the method of TestBed class. The compileComponents() is used to compile the components.


1 Answers

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.

like image 95
Paul Samsotha Avatar answered Sep 24 '22 02:09

Paul Samsotha