gpt4 book ai didi

reactjs - NextJS Router & Jest : How can I mock router change event

转载 作者:行者123 更新时间:2023-12-04 12:59:43 34 4
gpt4 key购买 nike

我正在使用 next-routes在我的 React 组件中,我在下面使用 useEffect要检测的代码块 Router更改事件:

useEffect(() => {
// THIS BLOCK WILL BE EXECUTED WHEN THE COMPONENT IS ALREADY MOUNTED AND SCREEN WOULD BE REDNDERED IN WHEN ROUTED CLIENT SIDE
const handleRouterChangeComplete = url => {
// console.log('INNNN handleRouterChangeComplete url = ', url);
// MY REST OF THE LOGIC HERE
};

// THIS BLOCK WILL BE EXECUTED WHEN THE SCREEN WOULD BE REDNDERED IN WHEN ROUTED CLIENT SIDE
Router.events.on('routeChangeComplete', handleRouterChangeComplete);
return () => {
Router.events.off('routeChangeComplete', handleRouterChangeComplete);
};
}, []);

我正在使用 jest为此组件编写单元测试用例并面临以下错误:
TypeError: Cannot read property 'on' of undefined

183 |
184 | // THIS BLOCK WILL BE EXECUTED WHEN THE SCREEN WOULD BE REDNDERED IN WHEN ROUTED CLIENT SIDE
> 185 | Router.events.on('routeChangeComplete', handleRouterChangeComplete);

任何人都可以帮我 mock Router Change事件?
谢谢

最佳答案

您可以使用 Router.events.emit('event-name') 触发相关的更改事件。 ;

代码取自 router implementation .

关于reactjs - NextJS Router & Jest : How can I mock router change event,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59961579/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com