Reactjs Jest/酶测试在使用钩子时抛出错误
我有一个简单的React组件,它使用useState钩子。这个组件在应用程序中正常工作,但是我的Jest测试给了我一个错误“钩子只能在函数组件的主体内部调用”。据我所知,我正确地调用了useState,同样,当我运行应用程序时,它工作正常 我正在使用react和react dom的16.8.4版本,npm ls对此进行了验证 以下是整个组件:Reactjs Jest/酶测试在使用钩子时抛出错误,reactjs,jestjs,enzyme,react-hooks,Reactjs,Jestjs,Enzyme,React Hooks,我有一个简单的React组件,它使用useState钩子。这个组件在应用程序中正常工作,但是我的Jest测试给了我一个错误“钩子只能在函数组件的主体内部调用”。据我所知,我正确地调用了useState,同样,当我运行应用程序时,它工作正常 我正在使用react和react dom的16.8.4版本,npm ls对此进行了验证 以下是整个组件: import React, {useState} from 'react'; import './ExampleComponent.css'; func
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;
import React,{useState}来自“React”;
导入“./ExampleComponent.css”;
功能示例组件(道具){
const[count,setCount]=useState(0);
const handler=()=>setCount(count+1);
返回(
这个组件是一个测试
试验
);
};
导出默认示例组件;
下面是相应的Jest测试(使用酶):
从“React”导入React;
从“./ExampleComponent”导入ExampleComponent;
描述(“”,()=>{
常量选项={
targetElementId:“伪元素id”
};
常量包装器=浅();
它('呈现一个div',()=>expect(wrapper.find('div').exists()).toBe(true));
});
我在一些资料中读到,酶对钩子不起作用,但我的一位同事没有这个问题。我比较了我们的package.json文件和webpack配置,没有发现任何差异。我使用与react ant完全相同的版本尝试了这段代码。 看起来您的问题与特定的酶版本或酶配置有关 我用“酶”:“^3.9.0”和“酶-适配器-反应-16”:“^1.10.0”进行了尝试
从“React”导入React;
从“酶”导入{shall};
从“酶”中导入*作为酶;
从'enzyme-Adapter-react-16'导入适配器;
从“/App”导入{ExampleComponent};
configure({adapter:newadapter()});
描述(“”,()=>{
常量选项={
targetElementId:“伪元素id”
};
常量包装器=浅();
它('呈现一个div',()=>expect(wrapper.find('div').exists()).toBe(true));
});
看来我太急切了。到目前为止(2019-03-12),这种酶还不能支持React钩。虽然我能够通过使用mount()而不是shallow()来运行测试,但似乎还有其他问题,我不知道Ezyme何时会支持这些特性。我会退回到使用早期版本的React并错过钩子,直到其中一种酶支持它们,或者我们决定停止使用酶。您是否尝试过使用挂载而不是浅?这很有效,谢谢!这是一个巨大的帮助,但它并没有回答为什么shallow()不起作用的问题。谢谢您的关注。我尝试按照@zsmogori的建议使用mount(),然后测试运行。我不太清楚这两者之间的区别,所以我无法猜测为什么这会很重要,但这让我摆脱了目前的困境。
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));
});
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));
});