How to write test case for url push in useEffect react hook?

被刻印的时光 ゝ 提交于 2020-06-01 05:49:28

问题


import { logout } from '../../actions/user.actions';

const Logout = () => {
      useEffect(() => {
        Router.push('/any');
      }, []);
    };

Test File

     afterEach(() => {
        jest.clearAllMocks(); 
      });

      afterAll(() => {
        jest.resetAllMocks(); // clear all the mocks.
      });

      it('Should check the route', () => {
        const wrapper = mount(<Logout />);
        expect(wrapper.find('LoadingMessage')).toBeTruthy();
        expect(useDispatch).toBeCalledTimes(1);
        const mDispatch = useDispatch();
expect(mDispatch).toBeCalledWith({ type: 'USER_LOGOUT' });
    expect(Router.push).toBeCalledWith('/');expect(mDispatch).toBeCalledWith({ type: 'USER_LOGOUT' });
    expect(mDispatch).toBeCalledWith('/');
     })
    })

This is my sample of code that I have written, I want to write a test case for this. So I can test the Router push is happening or not?

Wanting some idea or help.

Thanks in advance.


回答1:


Below unit test solution mocks useDispatch hook and next/router module without using a mock redux store. Using the mocked redux store and check the state of store after dispatching an action is closer to integration testing.

E.g.

index.jsx:

import React, { useEffect } from 'react';
import Router from 'next/router';
import { useDispatch } from 'react-redux';
import { logout } from './user.actions';
import { LoadingMessage } from './LoadingMessage';

export const Logout = () => {
  const dispatch = useDispatch();
  const props = {
    active: true,
    withOverlay: false,
    small: false,
  };
  useEffect(() => {
    dispatch(logout());
    Router.push('/');
  }, []);
  return (
    <div>
      <LoadingMessage {...props}>
        <div>Logging out, please wait...</div>
      </LoadingMessage>
    </div>
  );
};

user.actions.ts:

export function logout() {
  return {
    type: 'LOGOUT',
  };
}

LoadingMessage.jsx

export const LoadingMessage = ({ children }) => <div>{children}</div>;

index.test.jsx:

import { Logout } from './';
import { useDispatch } from 'react-redux';
import { mount } from 'enzyme';
import Router from 'next/router';

jest.mock('next/router', () => ({ push: jest.fn() }), { virtual: true });

jest.mock('react-redux', () => {
  const originalReactRedux = jest.requireActual('react-redux');
  const mDispatch = jest.fn();
  const mUseDispatch = jest.fn(() => mDispatch);
  return {
    ...originalReactRedux,
    useDispatch: mUseDispatch,
  };
});

describe('61928263', () => {
  afterEach(() => {
    jest.clearAllMocks();
  });
  afterAll(() => {
    jest.resetAllMocks();
  });
  it('should pass without using mock store', () => {
    const wrapper = mount(<Logout></Logout>);
    expect(wrapper.find('LoadingMessage')).toBeTruthy();
    expect(useDispatch).toBeCalledTimes(1);
    const mDispatch = useDispatch(); // get the mocked dispatch function
    expect(mDispatch).toBeCalledWith({ type: 'LOGOUT' });
    expect(Router.push).toBeCalledWith('/');
  });
});

The outcome for the test:

 PASS  stackoverflow/61928263/index.test.jsx (8.62s)
  61928263
    ✓ should pass without using mock store (37ms)

--------------------|---------|----------|---------|---------|-------------------
File                | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
--------------------|---------|----------|---------|---------|-------------------
All files           |     100 |      100 |     100 |     100 |                   
 LoadingMessage.jsx |     100 |      100 |     100 |     100 |                   
 index.jsx          |     100 |      100 |     100 |     100 |                   
 user.actions.ts    |     100 |      100 |     100 |     100 |                   
--------------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        9.601s


来源:https://stackoverflow.com/questions/61928263/how-to-write-test-case-for-url-push-in-useeffect-react-hook

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!