evkline
evkline

Reputation: 1511

How do I use Jasmine to spy on a function that is imported via an ES6 default export?

I am working on a Redux app & trying to create a spy using Jasmine on an ES6 default exported function. I have attempted a few different ways of spying on the function, including using a wildcard import to access the 'default' property of the import, but nothing I've tried has worked thus far. Below is an example, where I would want to test widgets.js and spy on the widget function. Is there a way to achieve this without having to change the way im exporting the function from widget.js?

widget.js

import { Map } from 'immutable';
import { CREATE_WIDGET } from 'actions';

const initialState = Map({
  id: undefined,
  name: undefined
});

export default function widget(state=initialState, action) {
  switch (action.type) {
    case CREATE_WIDGET:
      return state.update((widget) => widget.merge(action.widget));

    default:
      return state;
  }
}

widgets.js

import { OrderedMap } from 'immutable';
import { CREATE_ROOM } from 'actions';
import widget from './widget';

const initialState = OrderedMap();

export default function widgets(state=initialState, action={}) {
  switch (action.type) {
    case CREATE_ROOM:
      return state.set(action.widget.id, widget(undefined, action));

    default:
      return state;
  }
}

Upvotes: 36

Views: 27685

Answers (2)

Cory Lewis
Cory Lewis

Reputation: 709

jasmine has some issues spying on individually exported functions so the typical work around I have found is this. Hope this helps people

import * as Funcs from './funcs.ts';
const myFuncSpy : jasmine.Spy = jasmine.createSpy( 'myFunc' ).and.returnValue( <SOME_VALUE> );
spyOnProperty( Funcs, 'myFunc', 'get' ).and.returnValue( myFuncSpy );

Upvotes: 2

jdrush89
jdrush89

Reputation: 431

You say you tried importing the wildcard and spying on default? What was the issue with that approach? I just ran into this problem and doing this solved it for me:

import * as widget from './widget';

describe('widget spec', () => {
    beforeEach(() => {
        spyOn(widget, 'default');
    });
});

Upvotes: 43

Related Questions