Member-only story
ARTICLE
Testing with Node, Jest, and JSDOM
From Testing JavaScript Applications by Lucas da Costa
In this article, you’ll learn how to use Node and Jest to test code written to run in a browser.
Take 40% off Testing JavaScript Applications by entering fccdacosta into the discount code box at checkout at manning.com.
Baking in a professional kitchen is quite different from baking at home. At home, you won’t always have all the unique ingredients you would find on a chef’s shelves. You probably won’t have the same fancy appliances, or the same impeccable kitchen. Nevertheless, that doesn’t mean you can’t bake excellent desserts. You’ve just got to adapt.
Similarly, running JavaScript in a browser is significantly different from running JavaScript in Node. Depending on the occasion, the JavaScript code running in a browser can’t run in Node at all, and vice-versa. Therefore, for you to test your front-end application, you’ll have to jump through a few extra hoops, but it doesn’t mean you can’t do it. With a few adaptations, you can use Node to run JavaScript that has been written for the browser in the same way that Louis can bake mouth-watering cheesecakes at home without the fancy French cookware he’s got at the bakery.
Within a browser, JavaScript has access to different APIs and thus has different capabilities.
In browsers, JavaScript has access to a global variable called window
. Through the…