Use Jasmine to Test Functions in Browser
Explore how to run Jasmine unit tests specifically in a browser context to handle JavaScript functions that depend on browser APIs such as requestAnimationFrame. Understand configuring jasmine-browser-runner, setting up test file structures, and managing module imports to effectively test browser-based code.
Browser API
Up until now, we’ve been running Jasmine and the unit tests in a Node.js environment. That won’t be enough if we’re developing and maintaining a browser application.
Let’s say there’s a functionality in our app that relies on a browser API like requestAnimationFrame.
requestAnimationFrame(callback)is a way to tell the browser, “Hey, when you’re ready with the DOM calculations but before you paint that, let me have a chance to run some JavaScript (the callback).”
In the following code playground, there’s an attempt to test such functionality. It’s the same Jasmine setup we’ve been using until now. Try running it.
const SpecReporter = require('jasmine-spec-reporter').SpecReporter
jasmine.getEnv().clearReporters();
jasmine.getEnv().addReporter(
new SpecReporter({
// add jasmine-spec-reporter
spec: {
displayPending: true,
},
})
)
Looking in src/my.spec.js, there’s the line expect(requestAnimationFrame).toBeDefined();. It tries to verify that requestAnimationFrame is defined.
It fails, saying, “There’s no such thing as requestAnimationFrame. I have no idea what you’re talking about!”
And no wonder, because Jasmine is running in the context of Node.js, where requestAnimationFrame simply does not exist.
To run that test, we need to run Jasmine in the context of a browser.
Run Jasmine in browser
There’s an npm package that allows running Jasmine in the context of a browser.
The library jasmine-browser-runner supports a variety of browsers, including ...