albertogasparin/react-magnetic-di

Error: "Invalid hook call. Hooks can only be called inside of the body of a function component."

Closed this issue · 1 comments

I'm seeing the following error whenever I use <DiProvider /> inside jest:

Invalid hook call. Hooks can only be called inside of the body of a function component.

Screen Shot 2021-11-16 at 5 02 59 PM

Screen Shot 2021-11-16 at 5 04 52 PM

I thought I was doing something wrong but I tried this by building an MVP:

// jest spec
// SomeTest.spec.js
import { useState } from 'react'
import { DiProvider, di, injectable } from 'react-magnetic-di'
import { render } from '@testing-library/react'
import '@testing-library/jest-dom'

function useSomeHook() {
  return useState('dummy')
}

function Testing() {
  di(useSomeHook)
  const [dummy] = useSomeHook()
  return <div>{dummy}</div>
}

const useSomeHookDi = injectable(useSomeHook, () => ['testing'])
function WithDep() {
  return (
    <DiProvider use={[useSomeHookDi]}>
      <Testing />
    </DiProvider>
  )
}

test('loads and displays input text', async () => {
  const { getByText } = render(<WithDep />)
  expect(() => getByText('testing')).not.toThrow()
})

Have you configured the babel plugin for your tests too?
As if I copy your MVP in the tests example I can see it pass properly.