6

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.

2 Answers 2

11

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.

Sign up to request clarification or add additional context in comments.

Comments

0

If you have selector h2 inside div and you want to select inside selector h2 from Dom you use first BY.css to select div like:

el = de.query(By.css('div')).nativeElement

then use el.querySelector('h2') to select selector h2.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.