Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 4 Unit Test: de.query(By.css(...)) versus Native Web API of de.nativeElement.querySelector(...)

Is there any advantage to using el = de.query(By.css('h2')).nativeElement; over a native element API of el = de.nativeElement.querySelector('h2');? They provide the same result.

Just starting out with Angular 4 Unit Tests and wanted to know if there is any performance differences, or reasons to use one over the other since they accomplish the same job. Not sure I understand the convenience of using By.css(...), or what circumstance/reason you might use one over the other.

like image 342
mtpultz Avatar asked Jun 06 '17 22:06

mtpultz


1 Answers

The reason for using By.css instead of using querySelector and querySelectorAll is that your test might not be running in a complete browser, but in a lighter test environment instead.

Big projects usually build and run tests on a CI server (like TeamCity or Jenkins), the CI server might be running on a headless cloud server (that is, without a real monitor, nor a GUI), so not able to run Chrome or Firefox to run karma tests inside.

There are a number of alternative ways to run tests on such a server (see here for a list https://github.com/dhamaniasad/HeadlessBrowsers ).

While some of them simulate a complete headless browser (think of PhantomJS), they are quite heavy in terms of RAM and CPU, so others are lightweight but might not support a complete DOM implementation with all CSS selectors.

Using the By.css you make sure your test will run (and run consistently) also on platforms that does not support a complete DOM.

like image 172
Simone Gianni Avatar answered Oct 30 '22 03:10

Simone Gianni