0

Hello I'm new testing Hooks, so I'm really lost, tried to find the answer but no result.

So the question is, How can I test useEffect from this code?

Code:

const [ range, setRange ] = useState(DATE_OPTIONS.LAST_30_DAYS)
const [ isLoading, setIsLoading ] = useState(true)

const startLoading = () => setIsLoading(true)
const stopLoading = () => setIsLoading(false)

useEffect(() => {
    startLoading()
    fetchYearlyOptiDrive(range, objectId)
        .then(stopLoading)
        .catch(stopLoading)
}, [range, objectId])

And what I wanna test from the code is LoadingIndicator, check the props isLoading, if it's true or false.

<LoadingIndicator {...{ isLoading }} />

Test:

    test('should return the default value', () => {
        const wrapper = mount(<OptiDriveCard {...props} />)
        expect(wrapper.find('LoadingIndicator').props).toBeTruthy()
    })

Error:

Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined

Any suggestion?

Matt Oestreich
  • 8,219
  • 3
  • 16
  • 41
Jonathan
  • 469
  • 1
  • 6
  • 20
  • 1
    By the error you are showing, it seems that some component is not right (the error is stating that some component returns `undefined` instead of a string, class or a function). If you check this [sandbox](https://codesandbox.io/s/infallible-lake-g2ev3) you will see that the code runs as expected. – mgarcia Sep 26 '19 at 15:49
  • @mgarcia it was an error of import, sorry :( – Jonathan Sep 26 '19 at 15:52

1 Answers1

1

To check the value passed to a component, you can use the enzyme prop method. In your case:

expect(wrapper.find('LoadingIndicator').prop('isLoading')).toBe(true);
mgarcia
  • 5,669
  • 3
  • 16
  • 35
  • now this `TypeError: Cannot read property 'then' of undefined`, sorry I'm very noob :( – Jonathan Sep 26 '19 at 15:53
  • That would be your `fetchYearlyOptiDrive` method not returning a promise. You can read about promises [here](https://developers.google.com/web/fundamentals/primers/promises). – mgarcia Sep 26 '19 at 16:11