Easy apps with hyperHTML — 7, Testing
Tags: hyperhtml, javascript, webdev, tutorial
Published: 2019-06-04 16:27:08

Part 7 written by Trevor Ganus, {% user pinguxx %} {% user paritho %}

1. [Introduction, wire/bind](https://dev.to/pinguxx/easy-apps-with-hyperhtml-1-31cc)
2. [Events and components](https://dev.to/pinguxx/easy-apps-with-hyperhtml-2-hbi)
3. [Moar about components and simple state management](https://dev.to/pinguxx/easy-apps-with-hyperhtml-3-1m3l)
4. [Wire types and custom definitions (intents)](https://dev.to/pinguxx/easy-apps-with-hyperhtml-4-38k3)
5. [Custom elements with hyper](https://dev.to/pinguxx/easy-apps-with-hyperhtml-5-5hdl-temp-slug-7285698)
6. [Customizing my custom elements](https://dev.to/pinguxx/easy-apps-with-hyperhtml-6-h5b-temp-slug-4579110)
7. **Testing!**
8. [Async loading, placeholder and a Typeahead with hyper](https://dev.to/pinguxx/easy-apps-with-hyperhtml-8-async-loading-5d96)
9. [Handling routes](https://dev.to/pinguxx/easy-apps-with-hyperhtml-9-routing-59k0)
10. [3rd party libraries](https://dev.to/pinguxx/easy-apps-with-hyperhtml-10-3rd-party-libraries-2n7b)

![](https://thepracticaldev.s3.amazonaws.com/i/qedmndmqtwvnww2mjr1f.jpeg)


I’m not a big fan of having 100% code coverage, etc, etc, etc. But if we are writing components, they probably need to be tested as much as possible. We won't go super deep into testing, but we do want to show a few ways you can test your components and elements.

A small caveat before we begin: this post isn’t intended to cover everything you need to know about unit testing. Many other tutorials can teach you the basics of how to write code that tests well. Our goal is to show you how to use specific testing tools, with the understanding that you have a basic understanding of unit tests in general. With that out of the way, let’s get started!

### Enter Tressa

Yup, YAAT — Yet Another Andrea Tool. Tressa is a very simple testing utility that we are going to use to test our stuff. It gives us the ability to do synchronized tests and asynchronous tests. It also comes with a basic assert function. Tressa requires consolemd, a module that lets us print using markdown to the console, which is pretty neat. Let’s see an example:

{% stackblitz intermediate-testing-01 ctl=1 %}

> **Note** : we have to load tressa and consolemd with unpkg because for some reason stackblitz never finds echomd even if installed. Open the real console to see errors, the inner console from stackblitz doesn’t show them for some reason.

Let's dissect the code a bit to understand all the pieces

- `tressa.title` Starts a “section” of tests, by default title adds (“#”) for you
- `tressa.end` Ends the section of tests and returns the time spent on them
- `tressa and tressa.assert` This where you put your assertions with an optional comment as a second argument. You can use either one, there is no difference between them.
- `tressa.log` console out with markdown, useful to separate parts of your tests
- `tressa.async` Need to wait for an async operation? Use this wrapper. It returns a promise to test those cases.

You can see that tressa makes it very easy to test our code. Hopefully, you remember our table created with only `hyper.Component`. If not, here’s a quick refresh:

{% stackblitz basics-table-7 ctl=1 %}

> Open the real console to see errors, the inner console from stackblitz doesn’t show them for some reason.

### Components

First let’s load consolemd and tressa. Then, let’s add a test for the footer component in our table. This component doesn’t really do much, so testing should be straightforward. Open the console to see the test results. If you are doing async tests, don’t forget to call the `done()` callback when your test is finished.

{% stackblitz intermediate-testing-02 ctl=1 %}

Cool, let’s move on to the header component. For this one, let’s see if the `<thead>` is getting icons when we pass the sorted property

{% gist https://gist.github.com/pinguxx/489f9978d97a27b54f3b04570f5a66cd %}

Let’s also test the clicking on an `<a>` tag:

{% gist https://gist.github.com/pinguxx/0c4616819f04a55848e32ef27a2e6716 %}

And now, all the code together:

{% stackblitz intermediate-testing-03 ctl=1 %}

So far, our tests have been on components separated from the DOM. We instantiate the elements with the new keyword. Let’s wrap up the table testing with a test directly on the component already rendered:

{% stackblitz intermediate-testing-04 ctl=1 %}

We don’t need to write all the tests in this asynchronous way, but I like it since it separates sections of our tests better. Being familiar with the asynchronous tests now will help us later, when we write more complex tests.

![](https://cdn-images-1.medium.com/max/1000/1*-DMTBsco27Ad3zJ8209N5Q.png)

### Intents

In our component project, we also have a couple of intents — one for icons and one for dates. Let’s test those now. For now, let’s remove the component testing so it’s easier to focus on the intents.

{% gist https://gist.github.com/pinguxx/a4e3660dfd7235a7379ae9894bd64853 %}

Well… we found our first bug. If we pass “a”, which is an icon that doesn’t exist in [Octicons](https://octicons.github.com/), we get:

```
TypeError: Cannot read property ‘toSVG’ of undefined
```

Let’s fix the intent:

{% gist https://gist.github.com/pinguxx/1080faebaf7b8ee3ad1ff37d59a0882a %}

Sweet, our test passes with the updated code. Now let’s test the date intent:

{% gist https://gist.github.com/pinguxx/8e9f0b0997a4187f295dc939ea7133d1 %}

Err… that last test shows batman! `NaN/NaN/NaN`, let’s fix that:

```
if (!isNaN(newdate.getTime()) && typeof newdate.getMonth === ‘function’)
```

Yay! Let’s see the result:

{% stackblitz intermediate-testing-05 ctl=1 %}

![](https://cdn-images-1.medium.com/max/512/1*Bs54g93GAySCBSunqJdubg.jpeg)

### Custom elements

This is our table as a custom element:

{% stackblitz intermediate-ce-13 ctl=1 %}

Since we are already using the functions of the table, let’s rewrite those as tests. But first let’s add some utilities and then put all the tests in a single file.

Let’s see if we are actually loading a table first:

{% gist https://gist.github.com/pinguxx/a635d0ecfd29e129a34359ec86e40b49 %}

It’s there, cool! Notice we get the same result from `tressa()` as when we were using `tressa.assert()` in our previous tests. Now let’s test data:

{% gist https://gist.github.com/pinguxx/933885c31d06a515a9f312da23f5c323 %}

There are a couple of things we want to look at here. First, data will make a row appear, but since it doesn’t have any real data everything will be “-”… except date… lets update the intent to fix that with:

```
let formatted = ‘-’,
```

Second, data is more real and we see that we have data in our rows and the footer is updated.

Now let’s test the column functions: add/remove/update

### Add
{% gist https://gist.github.com/pinguxx/00de227b5da3b0b73bf538069f168e25 %}
### Remove
{% gist https://gist.github.com/pinguxx/99082692dff5f1ab08416d2ac4a8bf1a %}
### Update
{% gist https://gist.github.com/pinguxx/7b91026068fb3431ff5686ff529795aa %}


Last but not least, sorting:

{% gist https://gist.github.com/pinguxx/839128c9c04fa10f2fc46c6819670414 %}

Let’s see everything working together:

{% stackblitz intermediate-testing-06 ctl=1 %}

### Coverage

![](https://cdn-images-1.medium.com/max/320/1*c3fZfe4bPDmWbXpf2rc-MQ.jpeg)

We tested our code, but what if we want to see how much was tested? For this, Istanbul is our friend. We can’t run Istanbul from stackblitz (that I’m aware of), but let’s create a project in github to run it, and that will generate a coverage report.

For this kind of test we’ll need to have [Node.js](https://nodejs.org/en/) and [npm](https://www.npmjs.com/)installed. If you’re not familiar with these tools, [here is a great place to start](https://www.tutorialspoint.com/nodejs/nodejs_npm.htm).

First, we need to change a couple of things. Code-wise we need to remove the tests from index.js and created a file called test.js (clever right?). Then, we need to remove all the imports except intents and table. With those changes, our index.js file looks like:

{% gist https://gist.github.com/pinguxx/61f770bd5163886046c608ad52d42d6b %}

We also will need to setup the test environment, since we are not going to use a browser for our tests. Instead, we are going to use [basicHTML](https://github.com/WebReflection/basicHTML). BasicHTML is a lightweight, dumb, and simple implementation of the HTML standard” — and yes it’s a YAAT.

So our start of the test file looks like this:

{% gist https://gist.github.com/pinguxx/ef5d2208b6e9bfae2ed0df5c97a8657c %}

We bring tressa, then basicHTML, and we set it up. We are also bringing sizzle so we can make complex queries (sizzle is the selector engine used by JQuery so it’s a powerful tool). Then we load hyperHTML, and finally our tests with index.js.

Then, we setup our fake browser by making it ready and DOMContentLoaded. We can then add our table — just like regular HTML — by using a wire. That’s it! Let’s grab our table and run the same test we wrote previously.

Now, to run all of this we need a bunch more of dev dependencies. Add this to the package.json file and `npm i` away

{% gist https://gist.github.com/pinguxx/1131e2349b38a44f7585dcfb35cd0958 %}

The first part is just our dependencies for the tests. We added a script for running our test — nyc is the istanbul cli. Lastly, we setup nyc so it loads babel to transpile our code, and we add a couple of handy reporters. The HTML reporter will make it so we can look at a pretty web page.

Since we don’t need the classes to be transpiled lets add a .babelrc to customize the behavior.

{% gist https://gist.github.com/pinguxx/bd583dea3e848a9b03196ac5c6ec6140 %}

When testing we use Istanbul and we target firefox 52… why 52?? IDK, sounds like a good number and it was the old ESR :D.

aaaand then fire up a console terminal, navigate to the folder with your package.json, and enter the command

```
npm test
```

Hopefully you will see something like this:

![](https://cdn-images-1.medium.com/max/598/1*BF8olzLf8E5Zlb5qH072ig.png)

Open the coverage folder and open index.html to see the report… almost 100%… mm what are we missing? Take a peek at the Table.js file:

```
if (ElOrObj.nodeName === "HYPER-COLUMN") {
```

Apparently basicHTML is case sensitive. No problem, it’s an easy fix. Let’s do:

```
if (ElOrObj.nodeName && ElOrObj.nodeName.toLowerCase() === "hyper-column") {
```

npm test again, open the report… 100%

Yay! We did it! You can clone the full project here:

[pinguxx/easyapps-7-test1](https://github.com/pinguxx/easyapps-7-test1)

### Integration tests

For integration testing, I really like [cypress](https://www.cypress.io/). It’s very easy to use and powerful. It lets us create unit, end-to-end, and integration tests. Cypress also gives you the ability to see the state of your web page/app at each stage of the tests.

With integration testing, we are testing the page directly, so we need to add some things to make that happen. Time does not permit me to explain everything for this, but if you want a more detailed explanation, let me know and I can create a post detailing the process.

The tl;dr; goes like this:

- Add cypress/rollup/babel and plugins to package.json
- Add test/build scripts in package.json
- run cypress for the first time
- build (babel/bundle) index.js with all the modules used
- start a local server http-server -p 8081
- create a new integration test, table\_spec.js is what I called mine
- replicate tressa test and/or add more
- profit!!

![](https://cdn-images-1.medium.com/max/1024/1*kqt4GZ6dpT_aPY3IKNONrw.png)<figcaption>Test passed :D</figcaption>

For more information, check out the [cypress docs](https://docs.cypress.io/guides/overview/why-cypress.html#In-a-nutshell). You can also clone and run the tests yourself with this project:

[pinguxx/easyapps-7-test2](https://github.com/pinguxx/easyapps-7-test2)

I’m not the best at testing, but this shows a couple of ways to test our components and elements.

As always, let us know your feedback and what else you want to see in this series. Thanks for reading!

* * *