Jest: Question: guidance on mocking local es6 modules

Created on 25 Jan 2017  路  2Comments  路  Source: facebook/jest

I am having difficulty mocking a redux action on a local project and am looking for some guidance on how to proceed.

Here is an example of the files in play here:

actions/foo.js

import {
  CONST1,
  CONST2,
  CONST3,
} from '../somelib';

export const thing = {
  'key': 'value'
};

export const thingIWantToMock = (enabledState = 'Enabled') => (dispatch) => {
  // Implementation
}

actions/index.js

export * from './foo';
export * from './otherfoo';
export * from './otherfoo2';
export * from './otherfoo3';

Somewhere else I have a file that's actually consuming the es6 module I want to mock:

import { thingIWantToMock } from '../actions';

In jest I feel like I've tried everything and I cannot mock "thingIWantToMock"..

I have tried creating a files in actions/__mocks__/foo.js and actions/__mocks__/index.js and then using jest.mock('/path/to/actions/foo') or jest.mock('/path/to/actions') but that hasn't worked.

My most recent attempt was:

    jest.setMock('path/to/actions', require('path/to/actions/__mocks__/index'));

In all cases I cannot get my mock to be used when:

import { thingIWantToMock } from '../actions';

Is called.

Is there any guidance here? Tutorials I could look at, documentation I could read, etc?

Thank you!

Most helpful comment

Can you provide a repro for this on GitHub?

jest.mock('path/to/module', () => {鈥)
import {thing} from 'path/to/module';

this should definitely work if you are using babel-jest.

(Closing because this is a question)

All 2 comments

Can you provide a repro for this on GitHub?

jest.mock('path/to/module', () => {鈥)
import {thing} from 'path/to/module';

this should definitely work if you are using babel-jest.

(Closing because this is a question)

Disregard my comments. This was a bug on my part in the test suite where require-directory was recursively loading the specs when it should only be loading non-spec files.

Was this page helpful?
0 / 5 - 0 ratings