Stimulus: ReferenceError: MutationObserver is not defined

Created on 22 Mar 2018  路  4Comments  路  Source: hotwired/stimulus

I'm creating a test for a controller. But got this error when I do Application.start(). I'm using jest for testing.

Here's the code

import {Application} from 'stimulus'
import SomeController from '../controllers/some_controller'

describe('SomeController', () => {
  beforeEach(() => {
    const stimulusApp = Application.start()
    stimulusApp.register('some', SomeController)
  })
})

Most helpful comment

For anyone who comes across this:

Add mutationobserver-shim to your project:

yarn add mutationobserver-shim --dev

Include it in Jest setup. In your jest.config.js, update setupFilesAfterEnv array to include a setup file, like so:

// jest.config.js

setupFilesAfterEnv: [
  '<rootDir>/setup-jest.js'
],

Then, in the setup file, import the shim:

// setup-jest.js

import 'mutationobserver-shim';

All 4 comments

You'll need to run your tests in a browser or a simulated environment with MutationObserver support. I believe jest uses jsdom by default, which doesn't appear to support it: https://github.com/jsdom/jsdom/issues/639.

thanks @javan make sense.

For anyone who comes across this:

Add mutationobserver-shim to your project:

yarn add mutationobserver-shim --dev

Include it in Jest setup. In your jest.config.js, update setupFilesAfterEnv array to include a setup file, like so:

// jest.config.js

setupFilesAfterEnv: [
  '<rootDir>/setup-jest.js'
],

Then, in the setup file, import the shim:

// setup-jest.js

import 'mutationobserver-shim';
Was this page helpful?
0 / 5 - 0 ratings

Related issues

gerdriesselmann picture gerdriesselmann  路  3Comments

ngan picture ngan  路  3Comments

merwok picture merwok  路  4Comments

adrienpoly picture adrienpoly  路  3Comments

savroff picture savroff  路  4Comments