如何在Enzyme-Jest测试中定义Props?React组件测试报错求助
如何在Enzyme-Jest测试中为React组件定义Props以解决报错?
看起来你的LoginContainer组件在测试时因为缺少必要的props或者浏览器API模拟而报错了,别担心,我们一步步来解决这个问题:
首先,先明确你的组件依赖了几个关键props:location、history、goto、oktaRef,同时还用到了浏览器的sessionStorage和window.location,这些在测试环境中都需要提前模拟好。
1. 模拟基础Props
先创建一个包含所有必要props的模拟对象,用Jest的jest.fn()来模拟方法(比如history.push),方便后续做断言:
// 定义模拟props const mockProps = { // 可以根据测试场景设置search为空或带参数的字符串 location: { search: '' }, // 用jest.fn()模拟history.push方法 history: { push: jest.fn() }, goto: '/target-page', oktaRef: 'https://your-okta-auth-url.com' }; // 用Enzyme渲染组件时传入props import { shallow } from 'enzyme'; import LoginContainer from './LoginContainer'; const wrapper = shallow(<LoginContainer {...mockProps} />);
2. 模拟sessionStorage解决componentWillMount中的报错
你的组件在componentWillMount里调用了sessionStorage.setItem,测试环境默认没有这个全局对象,需要提前模拟:
// 在测试文件的开头或者beforeAll钩子中模拟sessionStorage beforeAll(() => { Object.defineProperty(window, 'sessionStorage', { value: { setItem: jest.fn(), getItem: jest.fn() }, writable: true }); });
这样当组件调用sessionStorage.setItem时,就不会因为找不到这个对象而报错了。
3. 测试okta方法时模拟window.location
组件的okta方法会修改window.location.href,测试时可以模拟这个全局属性来验证逻辑:
// 先清除原有的window.location,再模拟一个空的href属性 delete window.location; window.location = { href: '' }; // 调用组件实例的okta方法 wrapper.instance().okta(); // 断言window.location.href是否被正确设置为oktaRef的值 expect(window.location.href).toBe(mockProps.oktaRef);
4. 测试不同场景的props
如果要测试location.search有值的情况,只需要修改mockProps中的location即可:
const mockPropsWithSearch = { ...mockProps, location: { search: '?code=auth123' } }; const wrapper = shallow(<LoginContainer {...mockPropsWithSearch} />); // 之后可以断言history.push是否被调用,以及sessionStorage.setItem是否传入了正确的参数 expect(mockProps.history.push).toHaveBeenCalledWith(mockProps.goto); expect(window.sessionStorage.setItem).toHaveBeenCalledWith('hash', '?code=auth123');
核心思路就是:确保组件依赖的所有props和浏览器全局API在测试环境中都有模拟实现,这样组件运行时就不会因为遇到undefined而抛出错误了。
内容的提问来源于stack exchange,提问作者Amen Ra
相关产品推荐
相关产品推荐

