javascript - 在 useEffect 挂钩内测试路由器
问题描述
我有以下组件。
希望测试push
内部的路由器方法useEffect
是否正在使用特定路径和搜索进行调用。
import React from 'react';
import { compose } from 'redux';
import { withRouter } from 'react-router';
const MyComponent = ({
router: { push, location },
}) => {
const version = 'v2';
React.useEffect(() => {
push({
pathname: `/${version}/new_path`,
search: location.search ? location.search: '',
});
}, []);
return <div>Sample div text</div>
};
const higherOrder = compose(
withRouter,
aCustomHigherOrderC,
);
export default higherOrder(MyComponent);
这是我编写的测试,用于测试router
是否正确调用。
import React from 'react';
import { shallow } from 'enzyme';
import MyComponent from '../src/components/MyComponent';
jest.spyOn(React, 'useEffect').mockImplementation(f => f());
const props = {
router: {
push: jest.fn(),
location: {
search: '?param=1',
},
},
};
describe('MyComponent component tests', () => {
it('should work', () => {
const render = () => shallow(
<MyComponent {...props} />
);
expect(props.router.push).toHaveBeenCalledWith('/v2/new_path?param=1');
});
});
但是当我运行测试时出现以下错误。
错误:expect(jest.fn()).toHaveBeenCalledWith(expected)
预期的模拟函数已被调用:["/v2/new_path?param=1"] 但它没有被调用。
好像我什至没有进入useEffect
。确实尝试在那里添加一个断点,但我没有达到那个断点。我能否就我做错了什么以及如何测试使用正确路径和搜索参数调用它的路由器获得一些建议?谢谢。
解决方案
推荐阅读
- java - Hibernate - 交易:两个帐户之间的一致性
- android - 如何在 android studio 3.2 中解决执行 taskAction :app:mergeDebugResources
- hyperledger-fabric - 部署余额转移示例应用程序 hyperledger fabric-samples 时出错
- sql - SQL查询问题:从table1获取不在table2中的数据,而table2有2个条件
- java - 面临在本地模式下运行 Pig 的问题,在 java udf 中失败
- javascript - 如何通过点击功能从 html 到 javascript 获取“index-as”值?
- javascript - 确保结束日期大于开始日期并在适当的范围内
- angular - 是否有用于记录 Angular 项目的 WebStorm 插件?
- basic - 如果在 while 循环中产生条件,如何发出指令 - Liberty Basic
- android - 如何在android中使用volly将ArrayList数据发送到服务器