Jest - Mock module outside tested file

Viewed 929

I'm coming to you with mocking problem.

What I intend to achieve is possibility to mock several modules outside tested file.

I assume that first answer will be:

You can mock modules inside your tested file, although you are trying to do it differently.

I understand that it would work. However I really don't want to mock these modules in each test..

I have a setup file that looks like this:

const setup = (initialState, component) => {
  const store = TestState.getStore(initialState) // getting redux's state
  mockModules(initialState); // mocking modules
  const mounted = mount(
   <Provider store={store}>{component}</Provider>
  )
  return { store, mounted }
}

const mockModules = (initialState) => {
 jest.resetModules();
 jest.doMock(pathToModule, () => ({
   mockedFunction: () => ({ value: initialState.value }) // mocking function 
 }))
}

and this is how I'm using setup function in my test files:

describe('My test', () => {
  
  const setupTest = (initialState = {}) => {
     const {mounted, store} = setup(initialState, <MyComponent />);

     return {mounted, store}
  }

  it('first test', () => {
   const {mounted} = setupTest();
   expect(mounted.exists()).toBe(true);
  })
})

My problem is that these modules that I've mocked by mockModules function, they aren't mocked..

I've tried a lot of "workarounds" and neither of them worked. Any ideas?

0 Answers
Related