Read more

Jasmine: Fixing common errors during initialization

Henning Koch
February 23, 2022Software engineer at makandra GmbH

Due to the way we setup Jasmine tests in our projects, you may run into various errors when Jasmine boots.

Setting jasmineRequire on undefined

Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot

Jasmine 4 may fail with an error like this:

Uncaught TypeError: Cannot set properties of undefined (setting 'jasmineRequire')

This is due to issues in Jasmine's environment detection Show archive.org snapshot . It must be fixed by patching the Jasmine sources.

Fix for Webpacker

Add the package string-replace-loader to your package.json. If you're on Webpacker 5 (Webpack 4) the latest version you can use is 2.x.

Now add the following loader to your config/webpack/environment.js:

environment.loaders.prepend('fix-jasmine4-global-detection', {
  test: /jasmine-core\/lib\/jasmine-core\/jasmine\.js$/,
  use: [{
    loader: 'string-replace-loader',
    options: {
      search: 'window.toString() === \'[object GjsGlobal]\'',
      replace: 'window.toString() === \'[object Window]\''
    }
  }]
})

Fix for ESBuild / jsbundling-rails

Add the package esbuild-plugin-text-replace to your package.json.

Now add the following plugin to your esbuild.config.js:

const textReplace = require('esbuild-plugin-text-replace')
const esbuild = require('esbuild')

esbuild.build({
  ...
  plugins: [
    textReplace({
      include: /jasmine-core\/lib\/jasmine-core\/jasmine\.js$/,
      pattern: [
        ['let jasmineRequire;', 'let jasmineRequire; const global = window;'],
      ],
    }),
  ],
})

If you are on Jasmine < 4.3.0, use var instead of let in the code above.

Missing getJasmineRequireObj()

If you get this error:

Uncaught ReferenceError: getJasmineRequireObj is not defined

then you need a manually expose getJasmineRequireObj() to your specs.

Fix for Webpack

Add a file

// app/webpack/spec/support/jasmine_provider.js
import jasmineRequire from 'jasmine-core/lib/jasmine-core/jasmine.js'

export default function getJasmineRequireObj() {
  return jasmineRequire;
}

Then expose the provider in your config/webpack/environment.js:

const webpack = require('webpack')

environment.plugins.prepend('Provide', new webpack.ProvidePlugin({
  getJasmineRequireObj: ['spec/support/jasmine_provider.js', 'default'],
}))

Fix for ESBuild / jsbundling-rails

TODO.

Henning Koch
February 23, 2022Software engineer at makandra GmbH
Posted by Henning Koch to makandra dev (2022-02-23 11:36)