[英]how can I test if useState hook has been called with jest and react testing library?
I have this component that I would like to test using Jest and React testing library :我有这个组件,我想使用 Jest 和 React 测试库进行测试:
export function GenericDivider({ stepsHeader = [], componentsFactory = [] }) {
const [currentPage, changePage] = useState(0);
const Component = componentsFactory[currentPage] || (() => <></>);
return (
<div className="container page__container">
...
<a
href="#"
key={name}
onClick={e => {
e.preventDefault();
if (index < componentsFactory.length) changePage(index);
}}
className={`nav-link ${currentPage === index && 'active'}`}
>
{name}
</a>
...
</div>
);
}
export default memo(GenericDivider);
I would like to test if changePage is called when I fire a click, is there a way i can do that using Jest and React testing library ?我想测试当我点击时是否调用了 changePage,有没有办法使用 Jest 和 React 测试库来做到这一点?
I'm new to testing and I tried this but it doesn't seem to work我是测试新手,我试过这个,但它似乎不起作用
it('Should call changePage when button clicked', () => {
const changePage = jest.fn();
const { container } = render(
<GenericDivider
stepsHeader={['hamid', 'walid', 'khalid']}
componentsFactory={[() => <></>, () => <></>, () => <></>]}
/>,
);
const button = container.querySelector('a');
fireEvent.click(button);
expect(changePage).toHaveBeenCalled();
});
Short answer: don't.简短的回答:不要。
Testing an internal state variable very much goes against the philosophy behind react-testing-library.测试内部状态变量非常违背 react-testing-library 背后的理念。 That lib is focused on the user, and what the user can see.该库专注于用户以及用户可以看到的内容。 The user has no concept of a state variable.用户没有状态变量的概念。 Instead of testing that, think of the changes the user would see, and test for that.与其进行测试,不如想想用户会看到的更改,然后对其进行测试。 How is the UI updated? UI是如何更新的? What different markup or styling is displayed?显示了哪些不同的标记或样式? Consider how to test from the user's perspective, and you'll find your answers.考虑如何从用户的角度进行测试,您就会找到答案。
Check out react-testing-library's Guiding Principles for more context.查看 react-testing-library 的指导原则了解更多上下文。 Then take a look through this page for guidelines on which queries make the most sense for your use case.然后查看此页面,了解哪些查询最适合您的用例的指南。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.