【发布时间】:2021-09-12 23:59:51
【问题描述】:
假设我有一个这样的组件:
export function Click(props: { counter: number }) {
const [ counter, setCounter ] = useState(props.counter);
return (
<header className="App-header">
<h1 data-test="counter">{counter}</h1>
<button onClick={() => setCounter(counter + 1)}>
Click me
</button>
</header>
);
}
而我的测试文件是这样的:
import React from 'react';
import { mount } from "enzyme";
import App, { Click } from './App';
class Setup<Props> {
constructor(FunctionComponent: React.FC<Props>, props: Props) {
return mount(
<>
{FunctionComponent(props)}
</>
)
}
}
test("Doesn't work", () => {
const wrapper = new Setup(Click, { counter: 0 });
expect(wrapper.find(`[data-test="counter"]`)).toHaveLength(1);
});
这会返回一个错误:
Hooks can only be called inside of the body of a function component.
但我真的不知道如何解决它。 你看,我不能使用功能组件,因为它会破坏目的。 我的想法是创建一个库来帮助我编写测试,所以我想使用类。
【问题讨论】:
标签: reactjs typescript jestjs react-hooks enzyme