7

I am trying to do a SnapShot verification using Jest for my React App for one of the functional component. Here is the component and test file using Jest

import React, { useState } from 'react';
import useForm from 'react-hook-form';
import { useAppState } from 'Shared/store';
...

const Form = () => {

const {customReducer, dispatch} = useAppState();
const { register, handleSubmit, errors, reset } = useForm({});

//custom form methods

return (
<>
   <Form ...>
     ...
   </Form>
   ....
</>
);
export default Form;

and my test using Jest

import React from 'react';
import TestRenderer from 'react-test-renderer';
import ShallowRenderer from 'react-test-renderer/shallow';
import Form from '../form';

describe('<Form />', () => {
    test('Snapshot', () => {
    const tree = TestRenderer.create(<Form />).toJSON();
    expect(tree).toMatchSnapshot();
  });
});

and i was getting below error TypeError: Invalid attempt to destructure non-iterable instance

Tried with Enzyme as well but getting the same error. Spend good time in referring other related questions but couldn't figure out. Thank you.

skyboyer
  • 22,209
  • 7
  • 57
  • 64
siddhuKantipudi
  • 303
  • 4
  • 11

1 Answers1

5

Had a similar problem where Storybook threw Invalid attempt to destruct non-iterable instance on a component using hooks (useContext).

The solution was to initiate the context with a default value, createContext([{}, function() {}])

I found the solution here

Natan Williams
  • 1,447
  • 1
  • 8
  • 13
  • thank you. I ended up creating a mocking the StateProvider(using hooks) with FetchMock from '@react-mock/fetch'. I don't know if it best solution, but with this way, isolated the state from component. Here is working solution here. https://codepen.io/siddhukantipudi/pen/KKKrqpK – siddhuKantipudi Nov 15 '19 at 16:27
  • Thanks, while i try it i realized that the thing it's the initialization of the context, if you return an array, you have to init as an array with the values you want in there, createContext( [ ] ) createContext( [false, () => {}]), createContext( [ { }, () => {}]) . . . – Franco Manzur May 04 '20 at 15:03
  • It cannot be used while using react hooks inside of the stateless functional component – Marfin. F Dec 01 '20 at 17:05