Unit Testing of Custom Elements

During the past week, one of my major tasks was writing unit tests for 4 components using the web component tester. The web component tester (wct) brings together a series of tools that ensures the process is as seamless as possible. Please check out the documentations here .

The tools that came out of the box with WCT includes Mocha, as a testing framework, Chai for assertions, async, lodash, sinon and sinon-chai, text-fixture and allySuite. More information about these is available in the link above. The testing suite can be in javaScript or html.I went with html to maintain the format of the project's monorepo.

The steps involved in the unit testing are available here. Below is the description of the steps involved in the unit testing for observation status custom element. The first step was to create an observation JSON file that contains all the information in an fhir observation resource that can be locally imported. This was important because the hapi server that houses the fhir resources instances is not always available. Next , I created the html file that contains the testing code. The observation status is built with the material web component, "mwc-select". There are four options for the observation status including, Regsistered, Preliminary, Final and Amended. In proper functioning, the value for the observation status is determined by the value attribute or url passed to the "fhir-observation-status" tag. A snip of the component is shown below.

To write the unit test, I asserted that the value selected is equal to my assertion value and not equal to a wrong value. I also checked that the AJAX call returns the appropriate response.

To start the unit test, a fake server was created using sinon where mock XHR request can me made to recieve an AJAX response. The AJAX response is first tested. This is followed by the teardown() function that cleans up the server after the test. Next, the value for the observation status contained in the observation JSON file was confirmed using the assert functions. The results obtained from the test is presented below