gloriaJun / til

Lessoned Learned
3 stars 0 forks source link

react hook test with mocking useSelector and useDispatch #126

Open gloriaJun opened 3 years ago

gloriaJun commented 3 years ago

Version

Test Scenario

import { useCallback } from 'react';
import { useSelector } from 'react-redux';

// ...SKIP...

export function useAfterSignIn() {
  const { isTransferPortal, queryParams } = useSelector(appAccessPointSelector);

  const handleRouteAfterSignIn = useCallback(
    // ...SKIP...
    },
    [isTransferPortal, queryParams]
  );

  return {
    onRouteAfterSignIn: handleRouteAfterSignIn,
  };
}

Test Code

import { renderHook } from '@testing-library/react-hooks';
import * as reactRedux from 'react-redux';

import { mockWindonwLocation } from '@tests/utility';
import { history } from '@lib/history';
import { useAfterSignIn } from './useAfterSignIn';

describe('useAfterSignIn', () => {
  describe('onRouteAfterSignIn', () => {
    const useSelectorMock = jest.spyOn(reactRedux, 'useSelector');

    beforeEach(() => {
      useSelectorMock.mockClear();
    });

    it('should be redirect to bank main, if not set the prevPathname and not set url', async () => {
      useSelectorMock.mockReturnValue({
        isTransferPortal: false,
      });

      mockWindonwLocation({});

      const { result } = renderHook(() => useAfterSignIn());

      result.current.onRouteAfterSignIn();

      expect(history.location.pathname).toBe('/');
      expect(history.location.hash).toBe('');
      expect(history.location.search).toBe('');
    });
  });
});

Reference