4

With @testing-library/react-hooks I used to pass mocked store through initialProps just as mentioned in Advanced Hooks docs. Let's assume I have a code:

import configureMockStore from 'redux-mock-store'
import { Provider } from 'react-redux'

const initialState = {}
const customStore = configureMockStore(initialState)

// this wrapper is nicely reusable across all tests
const wrapper = ({ children, store = customStore }) =>
  <Provider store={ store }>
    {children}
  </Provider>

const useCustomHook = () => {
  const dispatch = useDispatch()
  useEffect(() => {
    dispatch({ type: 'ACTION' })
  }, [])
}

test('should get dispatched action', () => {
  renderHook(useCustomHook, {
    wrapper: wrapper,
    initialProps: {
      store: customStore
    }
  })

  expect(customStore.getActions()).toEqual([{ type: 'ACTION }])
})

If I run this code with RTL before update (version 10.4.5) and @testing-library/react-hooks everything works as expected. But after these packages have merged, wrapper property in renderHooks function doesn't accept any other properties except children.

First iteration lead me to this solution:

renderHook(useCustomHook, {
  wrapper: ({ children }) => (
   <Provider store={ customStore }>{children}</Provider>
  )
})

...that's not as good in reusability as my previous wrapper. Is there any good solution of this problem?

2
  • Did you find a solution? I have the same issue, want to renderHook, but hook uses state that it has not been provided without being wrapped, will want to pass multiple providers so want a helper, which i can overwrite state in the store with. Commented Oct 25, 2022 at 14:51
  • 1
    @Jeremy yep. I'll make an answer rn Commented Oct 27, 2022 at 9:36

1 Answer 1

4

The solution:

const customWrapper = (store) => ({ children }) =>
  // this function is mentioned in question
  wrapper({
    children,
    store
  })
  
test('Some test #1', () => {
  const mockedState = {}
  const mockedStore = configureMockStore(mockedState)

  const { result } = renderHook(() => useCustomHook(), {
    wrapper: customWrapper(mockedStore)
  })
})

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.