Testing Recipes for web components: Part 2 — Testing Forms and Custom Events

Adarsh Somani
2 min readJul 1, 2019

Go to Part 1 for basic setup and basic component testing

In this article we will try to test much more complex scenario then simple presentation.

Testing the search form

The above screenshot is taken from our live demo https://movie-app-892c6.firebaseapp.com/

There is a simple text box and button in our search form, if we type a new search term our movie grid will update, we have used custom events in the search form code.

Basic Setup

As previous article, we will include our required dependencies and create a renderer with opwn-wc’s fixture

I will skip basic tests, like component include a form, input etc and we will go straight to more advance tests

a) Test a form submit event

Consider the following piece from our code file

setUpSearch() {this.shadowRoot.querySelector('form').addEventListener('submit', (ev) => {ev.preventDefault();this.dispatchSearchEvent();});}//html
<input type="text" class="form-control" placeholder="Search Term"><button type="submit">Search</button></form>

On click of submit, code is calling a disaptchSearchEvent Function

To test the event listeners we will need fakes and stubs from ‘sinon’ library.

  1. We will add a spy on addEventListener
  2. We will call our function and will check if callback has been called or not.
it('should submit form ', async () => {//const el = await fixture('<search-form></search-form>');const form = el.shadowRoot.querySelector('form');const formSubmitSpy = sinon.spy(form, 'addEventListener');el.setUpSearch();expect(formSubmitSpy.calledWith('submit')).to.equal(true);});

b) Test a custom event

It is the tricky part, ‘Custom Events’ are a core functionality and used to communicate between web components, on firing ‘search’ custom event, our grid should re-render

dispatchSearchEvent() {const searchInput = this.shadowRoot.querySelectorAll('input')[0];this.dispatchEvent(new CustomEvent('search', {detail: {searchTerm: searchInput.value}}));return false;}

To test this

  1. We will create a new spy from sinon
  2. Spy will be called on firing search event inside test code
it('should dispatch event', async () => {const eventspy = sinon.spy()el.addEventListener('search', eventspy);el.dispatchSearchEvent();expect(eventspy.called).to.equal(true);})

That’s all in testing the forms and custom events. Please find a final code below

You can check the complete code here at https://github.com/inms-adarsh/movie-app-webc and demo is at https://movie-app-892c6.firebaseapp.com/