【问题标题】:TypeError: Invalid attempt to destructure non-iterable instance React/JestTypeError:对不可迭代实例 React/Jest 的解构尝试无效
【发布时间】:2020-03-10 16:36:15
【问题描述】:

我正在尝试使用 Jest 对我的 React 应用程序的一个功能组件进行 SnapShot 验证。这是使用 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;

以及我使用 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();
  });
});

而且我遇到了错误 TypeError: 无效的解构不可迭代实例的尝试

也尝试过 Enzyme,但得到了同样的错误。花很多时间参考其他相关问题,但无法弄清楚。谢谢你。

【问题讨论】:

  • 你会模拟你在组件中使用的任何钩子吗?
  • 你好,我有几个钩子。 useAppState(内部使用 useContext)和 useState。我没有嘲笑他们俩

标签: javascript reactjs jestjs enzyme destructuring


【解决方案1】:

有一个类似的问题,Storybook 使用钩子 (useContext) 将 Invalid attempt to destruct non-iterable instance 扔到组件上。

解决方案是使用默认值 createContext([{}, function() {}]) 启动上下文

我找到了解决方案here

【讨论】:

  • 谢谢。我最终使用来自“@react-mock/fetch”的 FetchMock 创建了一个模拟 StateProvider(使用钩子)。我不知道它是否是最好的解决方案,但是通过这种方式,将状态与组件隔离开来。这是这里的工作解决方案。 codepen.io/siddhukantipudi/pen/KKKrqpK
  • 谢谢,当我尝试它时,我意识到它是上下文的初始化,如果你返回一个数组,你必须初始化为一个包含你想要的值的数组,createContext([ ] ) createContext( [false, () => {}]), createContext( [ { }, () => {}]) 。 . .
  • 在无状态功能组件内部使用 react hooks 时不能使用
猜你喜欢
  • 1970-01-01
  • 2021-10-10
  • 2016-12-14
  • 1970-01-01
  • 1970-01-01
  • 2019-06-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多