【问题标题】:React + Redux : Testing redux hooksReact + Redux:测试 redux 钩子
【发布时间】:2021-05-27 18:18:19
【问题描述】:

已经 7 天了,我已尝试阅读有关此的所有博客,但似乎没有任何效果。

问题

我需要为我的 React FC 模拟 ```useSelector``` 和 ```useDispatch```。

组件

/* renders the list of the apis */
const ApiSection = ({ categories }) => {
  const [page, setPage] = useState(0);
  const [query, setQuery] = useState('');
  const [search, setSearch] = useState(false);

  const dispatch = useDispatch();
  useEffect(() => {
    dispatch(fetchAllApis({ page, category: categories, query }));
  }, [page, categories, dispatch, search]);

  // all these three are showing as undefined when consoled for UNIT TESTS !!!!!!!
  const { apiList, error, loading } = useSelector((state) => {
    return state.marketplaceApiState;
  });
  const renderApiCards = () => {
    let apis = Object.values(apiList);
    return apis.map((each) => (
      <ApiCard key={each.apiId} info={each} data-test="ApiCard" />
    ));
  };
  return (
    <div className="ApiSection" data-test="ApiSection">
      <div className="ApiSection__search">
      <div className="ApiSection__cards">{renderApiCards()}</div>
      <button onClick={() => setPage(page - 1)}>Previous</button>
      <button onClick={() => setPage(page + 1)}>Next</button>
    </div>
  );
};
export default ApiSection;

测试

const initialState = {
  marketplaceApiState: {
    apiList: {
      a123: { name: 'name', description: 'desc', categories: 'cat', apiId: 'a123'},
    },
  },
};
const mockDispatch = jest.fn();
jest.mock('react-redux', () => ({
  ...jest.requireActual('react-redux'),
  useSelector: () => initialState,
  useDispatch: () => mockDispatch,
}));

const setup = () => {
  const store = createTestStore(initialState);
  // I have also tried mount with Provider
  return shallow(<ApiListSection categories={['a']} store={store} />);
};

describe('ApiListSection Component', () => {
  afterEach(() => {
    jest.clearAllMocks();
  });

  test('Calls action on mount', () => {
    setup();
    expect(useSelector).toHaveBeenCalled();
    expect(mockDispatch).toHaveBeenCalled();
  });
});

错误

这是我得到的错误:

let apis = Object.values(apiList);

我真的很感激,卡了这么多天

【问题讨论】:

    标签: reactjs unit-testing react-redux jestjs enzyme


    【解决方案1】:

    理想情况下,您不应该模拟 hooks,而是应该模拟 store。

    你应该用这样的东西来模拟你的商店

    据我所知,酶不支持挂钩,您需要使用 @testing-library/react 来对使用挂钩的组件进行良好测试

    import { applyMiddleware, combineReducers, compose, createStore } from 'redux';
    import thunk from 'redux-thunk';
    import { homeReducer } from "../ducks/home";
    import { jobReducer } from '../ducks/job';
    import { toastReducer } from '../ducks/toast';
    
    const composeEnhancers = compose;
    
    const rootReducer = combineReducers({
        home: homeReducer,
        toast: toastReducer,
        job: jobReducer,
    });
    
    const enhancer = composeEnhancers(applyMiddleware(thunk));
    export function createTestStore() {
        return createStore(rootReducer, enhancer);
    }
    

    你可以参考我的POC repo here

    我在那里使用了一些众所周知的工具。所有内容都列在 repo 的 readme.md 中。

    【讨论】:

    • 我们可以在 google meet 上进行快速通话吗?我真的很感激
    • 当然不要在这里公开发布链接,但是。您可以将此对话转换为聊天并在此处发布链接。
    • 任何人阅读本文,如果您知道解决方案,请帮助或与我聊天
    猜你喜欢
    • 2020-07-11
    • 2019-11-11
    • 1970-01-01
    • 1970-01-01
    • 2020-05-17
    • 2019-03-22
    • 1970-01-01
    • 1970-01-01
    • 2020-05-03
    相关资源
    最近更新 更多