Skip to content
Advertisement

How to test cloned HTML templates and generated by JS HTML elements with Jest?

I have the following HTML:

JavaScript

And I have the following plain JS file script.js:

JavaScript

Basically, once the class Manager is instantiated, it calls the init() method. This method is fetching data from an API, and once fetched, it generates HTML elements for each element of the received data.list array. When an element is being generated, it first checks if a browser supports the HTML template. If it does – the template is being cloned and attributes are being set. If not – the elements are being created with document.createElement(). The generated <a> element will have a "target" attribute which depends on one of the settings – either "_self" or "_blank"

Everything work and the elements are being generated either way. However, now I need to test with Jest that they are in fact being generated, and when clicking on a link it should be opened either in a new window/tab, or in the same window, depending on the setting.

I’m very, very new to Jest and to testing. After some searching I tried to follow this example. So I created this test:

JavaScript

But this test fails with Expected number of calls: 1; Received number of calls: 0

I tried to call manager.init() after the instantiation, tried to set the template support checking to false and go directly to generating with document.createElement() part, tried to use beforeEach/afterEach (as in example)… The test keeps failing.

What am I doing wrong and how can I make it work? How can I test all those things?

Advertisement

Answer

In general perception, I think you should use a mocked data instead of getting data from external API.

  1. It will make your test much more faster.
  2. It will make your text much more stable.
  3. It will focus on what the test is meant to test. (The API / Internet Connection are not relevant for testing the creation of the template)

I believe you test will work fine if it will not have to “wait” for the async response.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement