Reactjs 使用React路由器v.5、useHistory、useSelector和useEffect测试React

Reactjs 使用React路由器v.5、useHistory、useSelector和useEffect测试React,reactjs,react-hooks,enzyme,history.js,react-testing-library,Reactjs,React Hooks,Enzyme,History.js,React Testing Library,我很难为保护某些路由并以编程方式重定向未经授权的用户的组件编写适当的测试。该组件如下所示: import { useEffect } from 'react'; import { useSelector } from 'react-redux'; import { useHistory } from 'react-router-dom'; import { isAuthed } from 'redux/selectors/auth'; const mapState = state =>

我很难为保护某些路由并以编程方式重定向未经授权的用户的组件编写适当的测试。该组件如下所示:

import { useEffect } from 'react';
import { useSelector } from 'react-redux';
import { useHistory } from 'react-router-dom';
import { isAuthed } from 'redux/selectors/auth';

const mapState = state => ({
  isAuthenticated: isAuthed(state),
});

const LoginShield = ({ children }) => {
  const { isAuthenticated } = useSelector(mapState);
  const history = useHistory();

  useEffect(() => {
    if (!isAuthenticated) {
      history.push('/login');
    }
  }, [isAuthenticated]);

  return children;
};

export default LoginShield;
我基本上希望检查组件是否重定向未经身份验证的用户,而不重定向经过身份验证的用户(两个基本测试用例)。我尝试了几种使用Jest/Ezyme或Jest/ReactTestingLibrary的方法,但没有找到好的解决方案

目前,我的测试一团糟,但我会分享它,以便有人能告诉我问题出在哪里:

import React, { useEffect } from 'react';
import { act } from 'react-dom/test-utils';
import { mount } from 'enzyme';
import { createStore } from 'redux';
import { Provider } from 'react-redux';
import { Router } from 'react-router-dom';
import rootReducer from 'redux/reducers';
import LoginShield from 'components/LoginShield/LoginShield';

describe('LoginShield component', () => {
  let wrapper;
  let historyMock;

  beforeEach(() => {
    const initialState = { auth: { loginId: 'Foo' } };
    const store = createStore(rootReducer, initialState);
    historyMock = {
      push: jest.fn(),
      location: {},
      listen: jest.fn(),
    };
    jest.mock('react-redux', () => ({
      useSelector: jest.fn(fn => fn()),
    }));
    wrapper = mount(
      <Provider store={store}>
        <Router history={historyMock}>
          <LoginShield>
            <h5>Hello Component</h5>
          </LoginShield>
        </Router>
      </Provider>,
    );
  });

  it('renders its children', () => {
    expect(wrapper.find('h5').text()).toEqual('Hello Component');
  });

  it('redirects to the login page if user is not authenticated', async () => {
    await act(async () => {
      await Promise.resolve(wrapper);
      await new Promise(resolve => setImmediate(resolve));
      wrapper.update();
    });
    // is the above necessary?


    console.log(historyMock.push.mock.calls);
    // returns empty array

    // ... ? 

  });

  it('doesn`t redirect authenticated users', () => {
    // .... ?
  });
});
import React,{useffect}来自“React”;
从'react dom/test utils'导入{act};
从“酶”导入{mount};
从“redux”导入{createStore};
从'react redux'导入{Provider};
从“react Router dom”导入{Router};
从“redux/reducers”导入rootReducer;
从“组件/登录字段/登录字段”导入登录字段;
描述('登录字段组件',()=>{
让包装纸;
让历史来模拟;
在每个之前(()=>{
const initialState={auth:{loginId:'Foo'};
const store=createStore(rootReducer,initialState);
历史模拟={
push:jest.fn(),
地点:{},
听:jest.fn(),
};
mock('react-redux',()=>({
useSelector:jest.fn(fn=>fn()),
}));
包装=装载(
你好组件
,
);
});
它('呈现其子对象',()=>{
expect(wrapper.find('h5').text()).toEqual('Hello Component');
});
它('如果用户未经过身份验证,则重定向到登录页面',异步()=>{
等待动作(异步()=>{
等待承诺。决心(包装纸);
等待新的承诺(resolve=>setImmediate(resolve));
wrapper.update();
});
//是否有必要这样做?
log(historyMock.push.mock.calls);
//返回空数组
// ... ? 
});
它('not redirect authenticated users',()=>{
// .... ?
});
});
欢迎任何提示!提前谢谢。:)