如何测试/模拟反应钩子?

hui*_*hui 8 javascript reactjs jestjs okta react-hooks

最近,我升级了 okta-react 库,并将应用程序转换为使用新的钩子。我现在正在更新我的测试。useOktaAuth()undefined。我希望能够模拟它,以便我可以在用户登录时进行测试。

\n\n
const { authState, authService } = useOktaAuth();\n\n// TypeError: Cannot destructure property `authState` of 'undefined' or 'null'\n
Run Code Online (Sandbox Code Playgroud)\n\n

为了解决这个问题,我尝试通过执行以下操作来模拟钩子:

\n\n
    jest.mock('@okta/okta-react', () => ({\n      useOktaAuth: () => {\n        return {\n          authState: {},\n          authService: {}\n        };\n      }\n    }));\n
Run Code Online (Sandbox Code Playgroud)\n\n

那\xe2\x80\x99 不起作用。我仍然对如何测试这些组件有任何想法吗?

\n\n

谢谢

\n

小智 6

你很接近:

jest.mock('@okta/okta-react', () => ({
  useOktaAuth: () => ({
    authState: { isAuthenticated: true},
    authService: { handleAuthentication: jest.fn() }
  })
}));
Run Code Online (Sandbox Code Playgroud)


小智 0

jest.mock('@okta/okta-react', () => ({
    useOktaAuth: () => {
 return {
   authState: {},
   authService: {}
   };
 }
 }));

 test('should render CreateDeploymentManifestPage and ShowDeploymentManifest', 
  () => {
  const myMock= jest.fn();

  const wrapper = shallow(<CreateDeploymentManifestPage />);
  const basicInfo = wrapper.find(DeploymentBasicInfo);
  expect(wrapper.containsAllMatchingElements([
   <DeploymentBasicInfo />,
  ])).toBe(true);
  });
Run Code Online (Sandbox Code Playgroud)