1

I'm testing my Login component which implements Microsoft authentication for login. I'm returning empty fragment from Login.js. How can I test this using React Testing library and jest?

import { useEffect } from 'react';
import { msalInstance } from './authConfig';

export const Login = () => {
  useEffect(() => {
    msalInstance
      .handleRedirectPromise()
      .then((tokenResponse) => {
        if (!tokenResponse) {
          const accounts = msalInstance.getAllAccounts();
          if (accounts.length === 0) {
            // No user signed in
            msalInstance.loginRedirect();
          }
        }
      })
      .catch((err) => {
        console.error(err);
      });
  }, []);

  return <></>;
};
samehanwar
  • 3,280
  • 2
  • 23
  • 26
Siri
  • 11
  • 1
  • RTL isn't really suited for components like this since there is no output. Instead you'll likely need to spy on `msalInstance` from the auth config. Since the component only makes a call, I would say testing it is sort of pointless. Test the function directly. – evolutionxbox Jul 05 '22 at 08:31
  • turn it into a hook and test it using https://react-hooks-testing-library.com/ – Derek Apr 09 '23 at 02:25

1 Answers1

0

a possible solution for this, is to get the root element of the rendered output and check for emptiness with the jsDom matcher function toBeEmptyDOMElement

test('test Login Component', () => {
  const { container } = render(<Login />);

  expect(container).toBeEmptyDOMElement();
});
samehanwar
  • 3,280
  • 2
  • 23
  • 26