...

/

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 Headless, which is what’s being used in the code playground below.

{
  "srcDir": "src",
  "srcFiles": [
    "**/*.?(m)js"
  ],
  "specDir": "spec",
  "specFiles": [
    "**/*[sS]pec.?(m)js"
  ],
  "random": true,
  "stopSpecOnExpectationFailure": false,
  "browser": {
    "name": "headlessChrome"
  },
  "helpers": [
    "helpers/**/*.?(m)js"
  ]
}
Successfully runs in browser

Looking at pec/my.spec.js, we see expect(requestAnimationFrame).toBeDefined();, the exact same line we saw earlier. But this time, the test passes.

The difference is that we’re running jasmine-browser-runner runSpecs. It starts a browser, which then runs the tests.

Different tests folder

We probably noticed that the .spec.js file is no longer in the /src folder and has moved in the /spec folder. That’s aligned with the default configuration of jasmine-browser-runner. Since the spec files don’t need to be part of the browser application bundle that gets shipped to the end user, having them in a separate folder makes sense. We want the users to see only the application, not the tests.

It’s possible to configure the source and test files’ locations using the spec and src properties in the configuration file. ...