Bill Woodward
Bill Woodward

Reputation: 43

Calling Enzyme.configure in jasmine helper

I'm using Enzyme with React 16 via Karma, Jasmine, and webpack. I have a test where I configure the Enzyme adapter in the beforeEach function:

import React from 'react';
import Enzyme, { shallow } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';

import App from 'app';

describe('App', () => {
  let wrapper;

  beforeEach(() => {
    Enzyme.configure({ adapter: new Adapter() });

    wrapper = shallow(<App />);
  });

  it('should render an h1 header', () => {
    expect(wrapper.type()).toBe('h1');
  });

  it('should render Hello, World!', () => {
    expect(wrapper.text()).toEqual('Hello, World!');
  });
});

This all works fine.

Since I don't want to have to do this in every Enzyme test, I tried to move that code to an enzyme_helper.js file:

import Enzyme from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';

Enzyme.configure({ adapter: new Adapter() });

I have added the file to the list of files loaded by Karma, and built it via webpack (so I can use ES6 format). I've verified (via a console.log and running through the debugger), that the helper gets loaded, but when the tests in the test file run, I get:

   Error:
         Enzyme Internal Error: Enzyme expects an adapter to be configured, but found none. To
         configure an adapter, you should call `Enzyme.configure({ adapter: new Adapter() })`
         before using any of Enzyme's top level APIs, where `Adapter` is the adapter
         corresponding to the library currently being tested. For example:
         import Adapter from 'enzyme-adapter-react-15';
         To find out more about this, see http://airbnb.io/enzyme/docs/installation/index.html

Any suggestions what I might be doing wrong?

Upvotes: 4

Views: 363

Answers (1)

Jonathan Felchlin
Jonathan Felchlin

Reputation: 36

You can't configure it in a helper, but you can create an Enzyme setup file which re-exports all Enzyme exports and import that in your tests rather than Enzyme.

/* test/enzyme.js */

import Enzyme from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import jasmineEnzyme from 'jasmine-enzyme';

Enzyme.configure({adapter: new Adapter()});

// I also like to use this file to initialize jasmine-enzyme
beforeEach(() => {
    jasmineEnzyme();
});

export * from 'enzyme';

Then in your tests, import your enzyme setup file rather than Enzyme.

/* myModule.test.js */

import {shallow} from './test/enzyme';

Upvotes: 0

Related Questions