Unit Testing Angular(2+) with JSDOM can be problematic unless you know the secret handshake that allows ZoneJS and JSDOM to coexist.
The great thing about Angular is that you can write Unit Tests from the presentation layer all the way down to calls to the server. But up until now, you either ran those tests in a browser, which doesn’t work well in a CI system, or you used PhantomJS, which tends to be REALLY slow! But there is a better way, and hopefully, by the time this post goes live, the patches needed to use JSDOM will be available. If not, I’ll show you the hack that I’ve found works and the pull request I’m hoping will go live.
This week we want to continue our series about Angular 2 by looking at the Unit Testing capabilities that Angular 2 provides for us. What we want to cover today is:
Tweaking Karma to avoid using the Browser Window
Tips to testing components
This article was written using Angular CLI version 1.0.0-beta.20-4 (Tip, if you are upgrading on windows, rm –rf node_modules dist temp just means to delete the three directories. You can do that part manually, or install bash for Windows and run the command in bash.)
But, isn’t the point of unit testing to allow us to test UNITs? Why artificially limit our ability to test units if we don’t need to? If we had the ability to create protected members, wouldn’t we tests those separately?
As I’ve mentioned before, I’m in the middle of putting together a React reference app and I’m doing it using Test Driven Development. The problem is, the standard tools for implementing ES2015 code coverage with Jest make it hard to see at a glance if you have 100% code coverage or not because of some issues with the way Jest tells Babel to do the transformations by default, the way Babel transforms the code and implements the auxiliaryCommentBefore option and the way that Istanbul parses the ignore next comments.
I’ve been working on solving this problem for the last month and a half off and on. I’ve even posted a question about this on Stack Overflow, so I’m pretty sure no one else has a solution for this yet. I’m not going to say my solution is the best way to solve this problem, but it is a solution, which is better than what we have so far.
There is also another side of Unit Tests. Some companies are so fixated they aspire to have 100% Unit Tests coverage and they make programmers write Unit Tests for legacy code for no reason. Just for the sake of having Unit Tests. … [I] wonder if you had any similar experiences and what you think about this approach. I guess the 100% extreme is better than no tests at all, but it can make the developers very bored and feeling useless.