Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 229
Alejandro Andersson Avatar asked Jun 12 '17 19:06

Alejandro Andersson


1 Answers

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

const store = mockStore(initialState);

like image 197
AryanJ-NYC Avatar answered Oct 03 '22 15:10

AryanJ-NYC