如何在API中测试useEffect与API的反应?

时间:2019-11-19 07:33:01

标签: reactjs unit-testing redux mocking jestjs

我有一个简单的react应用。 useEffect,然后执行操作ITEMS_GET以获取数据, 然后在dom中显示数据

import React, {useCallback, useEffect} from 'react';
import {useDispatch, useMappedState} from 'redux-react-hook';

function App() {
  useEffect(() => {
    dispatch({type: 'ITEMS_GET'});
  }, []);

  const mapState = useCallback(
    state => ({
      items: state.items
    }),
    []
  );
  const {items} = useMappedState(mapState);

  const dispatch = useDispatch();

  // {items.title}
  return <div>bla</div>;
}

export default App;

我有1个测试用例。在test useEffect测试块中。我想模拟API调用,获取数据,然后组件呈现数据。我不确定如何在此test useEffect测试块内使用useEffect,api调用编写测试。有人可以给我指示吗?

import React from 'react';
import App from './App';
import {configure, mount} from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import configureStore from 'redux-mock-store';
import {StoreContext} from 'redux-react-hook';
import {cleanup} from '@testing-library/react';
import MockAdapter from 'axios-mock-adapter';
import {act} from 'react-dom/test-utils';
import axios from 'axios';

let setUp, element;
const mockStore = configureStore();
configure({adapter: new Adapter()});
afterEach(cleanup);

describe('App', () => {
  beforeEach(() => {
    const initialState = {};

    const store = mockStore(initialState);

    // Set up the text area with theme and store
    setUp = () => {
      return mount(
        <StoreContext.Provider value={store}>
          <App />
        </StoreContext.Provider>
      );
    };
  });

  it('test useEffect', () => {
    const mock = new MockAdapter(axios);
    mock.onGet('/path/to/api').reply(200, {});

    act(() => {
      element = setUp();
    });

    // component debug
    console.log(element.debug());
  });
});

code in github

0 个答案:

没有答案