Adding Jasmine JavaScript specs to a Webpack(er) project

Updated . Posted . Visible to the public.

The goal is to get Jasmine specs running in a Rails project using Webpacker, with the browser based test runner. Should be easily adaptable to a pure Webpack setup.

Image

Step 1: Install Jasmine

yarn add jasmine-core

Step 2: Add two separate packs

Since we do not want to mix Jasmine into our regular Javascript, we will create two additional packs. The first only contains Jasmine and the test runner. The second will contain our normal application code and the specs themselves.

We cannot combine both into a single pack, since this will confuse Jasmine and cause it to swallow all backtraces.

// app/webpack/packs/jasmine.js

import 'jasmine-core/lib/jasmine-core/jasmine.css'

import 'jasmine-core/lib/jasmine-core/jasmine-html.js'
import 'jasmine-core/lib/jasmine-core/boot0.js'
import 'jasmine-core/lib/jasmine-core/boot1.js'

import 'jasmine-core/images/jasmine_favicon.png'
// app/webpack/packs/specs.js
// First load your regular JavaScript (copy all the JavaScript imports from your main pack).
// For example:

let webpackContext = require.context('../javascripts', true, /\.js(\.erb)?$/)
for(let key of webpackContext.keys()) { webpackContext(key) }


// Then load the specs

let specsContext = require.context('../spec', true, /\.js(\.erb)?$/)
for(let key of specsContext.keys()) { specsContext(key) }

You packs might not live in app/webpack, so adjust depending on your setup.

Lastly, add a sample spec to app/webpack/spec/, like

// app/webpack/spec/test_spec.js
describe('The truth', () => {
  it('is still true', () => {
    expect(true).toBe(true)
  })
})

Step 3: Add a /jasmine page in Rails

# config/routes.rb

Rails.application.routes.draw do
  # ...

  if Rails.env.development? || Rails.env.test?
    get 'jasmine', to: 'jasmine#index'
  end
end
# app/controllers/jasmine_controller.rb

class JasmineController < ApplicationController
  layout false

  def index
  end
end
-# app/views/jasmine/index.html.haml

!!!
%html
  %head
    = stylesheet_pack_tag 'jasmine', :media => 'all'
    %link{href: image_pack_tag('jasmine_favicon.png'), rel: 'icon', type: 'image/png'}

  %body
    = javascript_pack_tag 'jasmine'
    = javascript_pack_tag 'specs'

Step 4: Enjoy

Go to /jasmine and see your (hopefully) working setup.

Bonus step: Run Jasmine from your E2E tests

It is often useful to add an E2E test that opens that Jasmine runner and expects all specs to pass. This way you can see Jasmine failures in your regular E2E test runs.

Common initialization issues

You may run into various errors when Jasmine boots. See Fixing common errors during Jasmine initialization.

Tobias Kraze
Last edit
Henning Koch
Attachments
License
Source code in this card is licensed under the MIT License.
Posted by Tobias Kraze to makandra dev (2019-06-28 07:48)