Jest mock redux-store getState() used in module with redux-mock-store

Alejandro Andersson picture Alejandro Andersson · Jun 12, 2017 · Viewed 7.9k times · Source

So my implementation of the redux-store might not be the best and my knowledge of Jest is minimum-to-none..

I have three files which consists of...

  1. A module
  2. A React Component
  3. The (a normal) store, exported as default

My test file looks like this:

// file.test.js


jest.mock( 'store', () => jest.fn() )

// external
import React from 'react'
import configureStore from 'redux-mock-store'

// internal
import Component from 'components/Component'
import store from 'store'

describe( 'Test My Component', () => {
    const mockStore = configureStore()

    it ( 'should equal true', () => {
        const initialState = { active: true }

        store.mockImplementation(() => mockStore( initialState ))

        expect( store.getState().active ).toBe( true )
    } )
} );

The reason why I am mocking store is because inside <Component /> I am using a module which itself imports the same store and holds a few function that are making use of store.getState()...

So what this returns is

TypeError: _store2.default.getState is not a function

I did get around this by mocking the module call (which is used by the <Component />) instead, but I feel like I "should" be able to do this, as I have different initial states I want to try and not all are dependent on the module.

This is my very first post on SO, let me know If I should clarify anything!

Answer

AryanJ-NYC picture AryanJ-NYC · Dec 5, 2017

Do not import the store. We want to mock the store:

const store = mockStore(initialState);