...

/

Use Jasmine to Test Functions in Browser

Use Jasmine to Test Functions in Browser

Learn how to run Jasmine in the browser, set up a reporter for it, and use helpers.

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,
    },
  })
)
It fails to run because there’s no browser API

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 Chrome ...

Access this course and 1400+ top-rated courses and projects.