[尝试shallow(<LoginForm />)
时,出现以下错误Invariant Violation: Could not find react-redux context value; please ensure the component is wrapped in a <Provider>
。因此,为了解决此问题,我尝试了:
const wrapper = shallow(
<Provider store={store}>
<LoginForm />
</Provider>
);
但是,调试输出为:
<ContextProvider value={{...}}>
<LoginForm />
</ContextProvider>
但是我也想呈现LoginForm。我尝试解决此问题的其他方法:
wrapper.find(LoginForm).shallow();
shallow(
<Provider store={store}>
<LoginForm />
</Provider>
).dive();
wrapper.find(LoginForm).shallow();
shallow(<LoginForm />, {
wrappingComponent: Provider,
wrappingComponentProps: { store }
});
但是所有这些都会导致上述相同的错误。使用shallow
方法时,如何解决此问题?另外,LoginForm
使用了React钩子,包括useSelect
钩子,因此将存储传递到组件prop不是我要的解决方案。
您可以模拟useSelector,也方便模拟选择器功能
import React from 'react';
import { mount, shallow } from 'enzyme';
import { getIsAuthorized } from 'modules/auth/reducer';
import SignIn from '../SignIn';
jest.mock('modules/auth/reducer');
jest.mock('react-redux', () => {
const RealModule = jest.requireActual('react-redux');
return {
...RealModule,
useSelector: (fn) => fn(),
};
});
interface SetupProp {
isAuthorized: boolean;
}
describe('Page: SignIn', () => {
const setupWrapper = ({ isAuthorized }: SetupProp) => {
(getIsAuthorized as jest.Mock).mockReturnValue(isAuthorized);
return shallow(<SignIn />);
};
test('should render form', () => {
const wrapper = setupWrapper({ isAuthorized: false });
expect(wrapper).toMatchSnapshot();
});
});
登录组件:
const SignIn: FunctionComponent = () => {
//...
const isAuthorized = useSelector(getIsAuthorized);
//...
}