Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

react hook test with mocking useSelector and useDispatch #126

Open
gloriaJun opened this issue Jul 22, 2021 · 0 comments
Open

react hook test with mocking useSelector and useDispatch #126

gloriaJun opened this issue Jul 22, 2021 · 0 comments

Comments

@gloriaJun
Copy link
Owner

Version

  • "react": "^16.10.2",
  • "react-dom": "^16.10.2",
  • "react-redux": "^7.1.1",
  • "@testing-library/jest-dom": "^5.13.0",
  • "@testing-library/react": "^11.2.7",
  • "@testing-library/react-hooks": "^7.0.1"

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant