简单地使用react hooks in beta在使用jest时不起作用,并导致错误
不变冲突:钩子只能在函数组件的主体内调用。
尽管环顾四周,我没有看到使用react钩子的Jest的工作示例。是的,我知道它是测试版,但让我们现在标记它。
https://github.com/ghinks/jest-react-hook-issue.git
const MyDiv = () => {
const [count, setCount] = useState(0)
const clickHandler = () => { setCount(count + 1);
console.log(`clicked ${count}`) }
return (
<div onClick={clickHandler}>
ClickMe {count}
</div>
)
}
即使是简单的测试
import { MyDiv } from './App';
describe('Test Component using hooks', () => {
test('MyDiv', () => {
const div = MyDiv();
expect(div).toMatchSnapshot();
})
});
将失败,并出现不变错误。
我希望这能真正起作用。
发布于 2018-12-26 19:35:01
看起来像是简单的更改
describe('Test Component using hooks', () => {
test('MyDiv', () => {
expect(<MyDiv/>).toMatchSnapshot();
})
});
解决了这个问题
发布于 2018-12-25 20:54:52
问题在于错误说明了什么。函数组件不应该被直接调用。
它应该如the reference所示:
import renderer from 'react-test-renderer';
...
const myDiv = renderer.create(<MyDiv/>).toJSON();
expect(myDiv).toMatchSnapshot();
https://stackoverflow.com/questions/53925317
复制相似问题