how to test/mock out react hooks?
Asked Answered
L

5

8

Recently I upgrade the okta-react library and have transitioned the app to use the new hooks. I am updating my tests now. useOktaAuth() is undefined. I want to be able to mock it out so I can test when a user is logged in.

const { authState, authService } = useOktaAuth();

// TypeError: Cannot destructure property `authState` of 'undefined' or 'null'

In order to fix that, I tried mocking the hook by doing:

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

That isn’t working. I still get Any ideas on how to test these components?

Thanks

Lyle answered 26/3, 2020 at 21:44 Comment(0)
P
5

You were close:

jest.mock('@okta/okta-react', () => ({
  useOktaAuth: () => ({
    authState: { isAuthenticated: true},
    authService: { handleAuthentication: jest.fn() }
  })
}));
Pindling answered 29/9, 2020 at 13:43 Comment(4)
Does anyone know how to reset this so that isAuthenticated could go between true and false? This satisfies the requirements of the dependencies but, I can't do it in a beforeEach or beforeAll hook as the test can't find the dependencies within that scope.Shedevil
Hello @RyanHamblin, were you able to resolve this? I'm facing similar issue.Lilli
@Lilli indeed, I solved it by not worrying about those details for now lol..Shedevil
I share the need to update the isAuthenticated value by test.Cracksman
P
4

After continuous research and work, this worked for me.

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

describe("Login", () => {
  test("should ", () => {
    const wrapper = shallow(<Login authService={null} />);
    expect(wrapper.length).toBe(1);
  });
});

Note: I passed authService param to the component.

Photoneutron answered 20/1, 2021 at 9:6 Comment(1)
Thank you, after hours of struggle this finally works!Schoolroom
G
2

I had almost the same message saying

TypeError: Cannot destructure property 'authState' of '(0 , _oktaReact.useOktaAuth)(...)' as it is undefined.**"

Component's part:

import { useOktaAuth } from "@okta/okta-react";

const Login = () => {
const { authState } = useOktaAuth();
...

TEST:

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

describe("<Login /> component tests", () => {
  it("Should render Login component", done => {
      const wrapper = shallow(<Login/>);

      setImmediate(() => {
          wrapper.update();
          try {
              // Your assertion here
              done();
          } catch (error) {
              done.fail(error);
          }
      });
  });

});

Geronimo answered 10/4, 2020 at 12:50 Comment(1)
Any idea how to mock the <Security> component?Experiment
P
1

in addition to Elmatsidis Paul answer I had to add 1 more mock to cover both useOktaAuth and withOktaAuth:

jest.mock('@okta/okta-react', () => ({
    useOktaAuth: () => {
        return {
            authState: {},
            authService: {}
        };
    },
    withOktaAuth: (x: any) => x
}));
Pelting answered 27/6, 2020 at 16:48 Comment(1)
Any idea how to mock the <Security> component?Experiment
H
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);
  });
Hankypanky answered 31/3, 2020 at 8:28 Comment(3)
just write mock outside the test component , it will work. It worked for me.Hankypanky
CreateDeploymentManifestPage is component which contains another component DeploymentBasicInfo. CreateDeploymentManifestPage is using useOktaAuth hooks to get authState and authService.Hankypanky
Any idea how to mock the <Security> component?Experiment

© 2022 - 2024 — McMap. All rights reserved.