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 templateUrl
s 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?
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.
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.
In what circumstances should I call this method, and why?
If you're using webpack (if configured properly), the build will compile the templateUrl
s into inline template
s 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With