使用Jest & Enzyme测试时设置URL参数?解决params未定义报错
修复React组件测试中
Cannot read property 'params' of undefined错误 这个错误很常见——你的Search组件在构造函数里依赖了props.match.params,但测试时你只传了shows props,没给match,所以this.props.match是undefined,自然读不到params啦。
有两种简单的修复方式,看你测试场景选:
方法一:直接传入match props(最直接)
既然组件需要match这个props,那测试时直接给它就行。你可以根据测试需求设置searchTerm,或者传个空的params对象让组件的逻辑正常运行:
修改后的测试代码:
test("Search should render correct amount of shows", () => { // 按需设置searchTerm,或者传空params也可以 const component = shallow( <Search shows={preload.shows} match={{ params: { searchTerm: "test-query" } }} /> ); expect(component.find(ShowCard).length).toEqual(preload.shows.length); });
如果不需要特定的搜索词,传空params也能让组件的typeof判断生效,把searchTerm设为空字符串:
match={{ params: {} }}
方法二:用MemoryRouter模拟路由环境(适合完整路由场景)
如果你的组件依赖React Router的路由上下文(比如除了match还用到history之类的),可以用react-router-dom提供的MemoryRouter来包裹组件,模拟真实的路由环境:
首先导入MemoryRouter:
import { MemoryRouter } from 'react-router-dom';
然后修改测试代码(注意这里要用mount而不是shallow,因为shallow不会渲染外层的MemoryRouter,组件拿不到路由上下文):
test("Search should render correct amount of shows", () => { const component = mount( <MemoryRouter initialEntries={["/search/test-query"]}> <Search shows={preload.shows} /> </MemoryRouter> ); expect(component.find(ShowCard).length).toEqual(preload.shows.length); });
initialEntries用来设置初始的路由路径,这样组件就能通过路由上下文拿到match.params.searchTerm了。
两种方法都能解决你的问题,要是只是测试组件的渲染逻辑,方法一更简单高效;要是需要模拟完整的路由行为,方法二更合适。
内容的提问来源于stack exchange,提问作者IceStrength
相关产品推荐
相关产品推荐

