DOM Manipulation
Another class of functions that is often considered difficult to test is code that directly manipulates the DOM. Let's see how we can test the following snippet of jQuery code that listens to a click event, fetches some data asynchronously and sets the content of a span.
Again, we create a test file in the __tests__/
folder:
The function being tested adds an event listener on the #button
DOM element, so we need to set up our DOM correctly for the test. Jest ships with jsdom
which simulates a DOM environment as if you were in the browser. This means that every DOM API that we call can be observed in the same way it would be observed in a browser!
We are mocking fetchCurrentUser.js
so that our test doesn't make a real network request but instead resolves to mock data locally. This ensures that our test can complete in milliseconds rather than seconds and guarantees a fast unit test iteration speed.
The code for this example is available at examples/jquery.