使用钩子时 Jest/Enzyme 测试抛出错误

Posted

技术标签:

【中文标题】使用钩子时 Jest/Enzyme 测试抛出错误【英文标题】:Jest/Enzyme test throws error when using hooks 【发布时间】:2019-08-02 02:35:41 【问题描述】:

我有一个使用 useState 挂钩的简单 React 组件。该组件在应用程序中正常工作,但我的 Jest 测试给了我错误“只能在函数组件的主体内调用 Hooks”。据我所知,我正确地调用了 useState,并且在我运行应用程序时它再次运行良好。

我正在使用 react 和 react-dom 的 16.8.4 版本,已通过 npm ls 验证。

这是整个组件:

import React, useState from 'react';
import './ExampleComponent.css';

function ExampleComponent(props) 
  const [count, setCount] = useState(0);
  const handler = () => setCount(count + 1);
  return (
    <div className='example-component'>
      <span>This component is a test</span>
      <button onClick=handler>Test</button>
      <input readOnly=true value=count></input>
    </div>
  );
;

export default ExampleComponent;

这里是对应的 Jest 测试(使用 Enzyme):

import React from 'react';
import ExampleComponent from './ExampleComponent';

describe('<ExampleComponent />', () => 
  const options = 
    targetElementId: 'fake-element-id'
  ;
  const wrapper = shallow(<ExampleComponent options=options />);
  it('renders a div', () => expect(wrapper.find('div').exists()).toBe(true));
);

我在一些资料中读到 Enzyme 不适用于钩子,但我有一位同事没有遇到此问题。我比较了我们的 package.json 文件和 webpack 配置,没有发现任何差异。

【问题讨论】:

你试过用mount代替shallow吗? 行得通,谢谢!这是一个巨大的帮助,但它并没有回答为什么 shallow() 不起作用的问题。 【参考方案1】:

看来我太热心了。截至目前 (2019-03-12) Enzyme 还不支持 React Hooks。虽然我能够通过使用 mount() 而不是 shallow() 来运行我的测试,但似乎还有其他问题,我不知道 Enzyme 何时会支持这些功能。在 Enzyme 支持它们或我们决定停止使用 Enzyme 之前,我将回退到使用早期版本的 React 并错过钩子。

【讨论】:

【参考方案2】:

我用完全相同版本的 react ant 尝试了这段代码。 您的特定酶版本或酶配置似乎存在问题。

我用 "enzyme": "^3.9.0" 和 "enzyme-adapter-react-16": "^1.10.0" 试过了

import React from 'react';
import  shallow  from 'enzyme';
import * as Enzyme from "enzyme";
import Adapter from 'enzyme-adapter-react-16';
import ExampleComponent from './App';

Enzyme.configure( adapter: new Adapter() );

describe('<ExampleComponent />', () => 
  const options = 
    targetElementId: 'fake-element-id'
  ;
  const wrapper = shallow(<ExampleComponent options=options />);
  it('renders a div', () => expect(wrapper.find('div').exists()).toBe(true));
);

【讨论】:

感谢您查看此内容。我尝试按照@zsmogori 的建议使用 mount() 并运行测试。我对差异的了解还不够,无法猜测它为什么重要,但它让我克服了当前的障碍。

以上是关于使用钩子时 Jest/Enzyme 测试抛出错误的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 JEST、Enzyme 在 React 中测试自定义钩子?

使用 React Suspense 和 React.lazy 子组件进行 Jest/Enzyme 类组件测试

如何使用 jest 和酶测试 onClick() 函数和 useState 钩子

React / Enzyme:运行 Jest / Enzyme 测试时出现 Invariant Violation 错误

使用 Jest/Enzyme 测试异步 mapDispatchToProps 操作会出错

如何使用 jest/enzyme 测试 useEffect 与 useDispatch 挂钩?