in Coding

AngularJS tests with mocked HTML documents

Most of the time, testing AngularJS applications means testing JavaScript. We test services and we test controllers. But what about directives? What about components? How do we test compiled and injected AngularJS code?


But before we start, here’s the running Plunker with the complete example:

Testing directives/components

Around a year ago I wrote a post on testing AngularJS directives with Jasmine. Let’s take a look at this article with a slightly modified example. While I used a directive in my last post back in 2016, we use one of AngularJS’ components, now. It’s 2017!

Here’s the component:

The component shows a simple text field which is required. The textForm becomes valid if some text is filled into this required text field.

The test

Testing this simple component is very straight forward. We just need to compile the HTML and run our tests against it. As AngularJS components use an isolated scope, we need to call element.isolateScope() to get the scope (including our form) of the component.

So what about the document?

Although we compiled some HTML code in the example above, we didn’t use any test document! There was no need. So let’s extend our example a little bit and introduce some necessity to use a test document.

Image the following: We have some use case where we need to generate code. If an user has not entered his phone number yet, we display an input form. If the user has already entered his phone number, we display some text (“Thank you for entering your phone number!“). While we could easily use some ng-if or ng-show construction, we decided to do it with code generation.

This use case could look like this:

We define a component called generator. This component has a very simple template, containing a placeholder div where we want to inject some other code. The main point is, that we are using the $document service. This service operates on the current document and is our way to create a mock document. But first, let’s see what happens if we don’t use a mock document.

Because the generator directive appends code to the document (inside #component-container) we need to add the compiled generator directive to the document, too!

The important points are:

  • We compile the generator directive and append it to the document.
  • Any code generated by the generator directive will be placed inside the document.
  • We need to clean the document after every test!

And by the way, here’s the Plunker again:

Best regards,

Write a Comment