使用钩子时,Jest / Enzyme测试会引发错误

问题描述 投票:1回答:2

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

我正在使用版本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配置,但没有发现任何差异。

reactjs jestjs enzyme react-hooks
2个回答
3
投票

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


0
投票

我尝试使用完全相同版本的反应蚂蚁它的代码。看起来您的问题与特定的酶版本或酶配置有关。

我尝试用“酶”:“^ 3.9.0”和“酶 - 适配 - 反应-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));
});
© www.soinside.com 2019 - 2024. All rights reserved.