oidc-react icon indicating copy to clipboard operation
oidc-react copied to clipboard

Testing components with oidc-react.

Open JairContreras opened this issue 4 years ago • 1 comments

Hi team, I'm currently working with this library. I have and assigment that I have to do unit testing to my components. How can I inject a user to <AuthProvider>?

JairContreras avatar Jul 08 '21 15:07 JairContreras

Assuming you're using jest, you can do fairly typical things to override what useAuth is going to do. I do something like:

import { useAuth } from 'oidc-react'; 
jest.mock('oidc-react');

Most times I don't need oidc-react in my tests. So this works for me. Then I mock out the return value of the useAuth hook:

(useAuth as any).mockReturnValue({
  // Indicate if oidc-react is still loading or not for your tests
  isLoading: false,
  // Overwrite AuthContext options as needed. Plug in user auth data too!
  signIn: jest.fn(() => Promise.resolve()),
  userData: {} as User,
  // You can stub out userManager specifics here if needed. I put in a few examples I've used for some tests
  userManager: {
    signinSilent: jest.fn(() => Promise.resolve()),
    signinRedirect: jest.fn(() => Promise.resolve()),
  },
});

After that I just adjust what I need to return in my tests accordingly.

pseudoramble avatar Aug 19 '21 20:08 pseudoramble

Hey!

I'm closing this for now, but feel free to open a new issue or let me know if you think this should be re-opened!

simenandre avatar Mar 01 '23 18:03 simenandre