Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to test/mock out react hooks?

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

like image 829
huihuihui Avatar asked Dec 31 '22 05:12

huihuihui


1 Answers

You were close:

jest.mock('@okta/okta-react', () => ({
  useOktaAuth: () => ({
    authState: { isAuthenticated: true},
    authService: { handleAuthentication: jest.fn() }
  })
}));
like image 140
Marc Jacobs Avatar answered Jan 13 '23 15:01

Marc Jacobs