Редуктор возвращает состояние как «неопределенное» во время модульного тестирования с ферментом - PullRequest
0 голосов
/ 17 октября 2018

Тестирование компонента подключения Redux: случай, когда я пытаюсь проверить ожидаемый результат от конкретного действия FETCH_COUNTRY_LIST, завершается неудачей. Мне нужно добавить специальное промежуточное программное обеспечение в мой mockStore.

  REACT-REDUX (Mount + wrapping in <Provider>) ClearAll Component
    ✓ +++ contains ClearAll component
    ✓ +++ contains clear All text
    ✓ +++ check action on dispatching 
    ✓ +++ check reducer INITIAL_STATE
    1) +++ check reducer FETCH_COUNTRY_LIST

Я не уверен, почему состояние становится неопределенным для countryList и selectedCountries. Я добавил оболочку.Update ().Есть ли что-то, что я делаю неправильно в приведенном ниже тестовом примере.

import React from 'react';
import expect from 'expect';
import { mount } from 'enzyme';
import { Provider } from "react-redux";
import configureMockStore from 'redux-mock-store';
import ClearAllFilters from './ClearAllFilters';
import { deselectAllCountry, deselectAllRegion, deselectAllSector } from '../../actions/filterActions';
import filtersReducer from '../../reducers/filtersReducer/filtersReducer';
//import { COUNTRY_LIST } from '../../constants/filterConstants';

const mockStore = configureMockStore();

const store = mockStore({filters:
{
  countryList: [],
  regionList: [],
  sectorList: [],
  isAllSelected: false,
  isAllSelectedR: false,
  isAllSelectedS: false,
  selectedCountries: [],
  selectedRegions: [],
  selectedSectors: []
}
});

const initialState = {
  countryList: [],
  regionList: [],
  sectorList: [],
  isAllSelected: false,
  isAllSelectedR: false,
  isAllSelectedS: false,
  selectedCountries: [],
  selectedRegions: [],
  selectedSectors: []
};

const wrapper = mount(<Provider store={store}><ClearAllFilters /></Provider>);

//*************Testing for ClearAllFilters React Component**********
describe('REACT-REDUX (Mount + wrapping in <Provider>) ClearAll Component',()=>{

  //Ensures it clears out all actions from our mockStore before each test suite.
  beforeEach(() => {
    store.clearActions();
  });

  it('+++ contains ClearAll component', () => {
    expect(wrapper.find(ClearAllFilters).length).toEqual(1)
  });

  it('+++ contains clear All text', () => {
    expect(wrapper.text()).toEqual('Clear All')
  });

  //Unit tests for Redux Action Creators.
  it('+++ check action on dispatching ', () => {
    let action
    store.dispatch(deselectAllCountry())
    store.dispatch(deselectAllRegion())
    store.dispatch(deselectAllSector())
    action = store.getActions()
    expect(action[0].type).toBe('COUNTRIES_DESELECT_ALL')
    expect(action[1].type).toBe('REGIONS_DESELECT_ALL')
    expect(action[2].type).toBe('SECTORS_DESELECT_ALL')
  });

  //Unit test for Redux Reducers.
  it('+++ check reducer INITIAL_STATE', () => {
    expect(filtersReducer(undefined, { type: 'dummy_action' })).toEqual(initialState);
  });

   it('+++ check reducer FETCH_COUNTRY_LIST', () => {
     const expectedState = {
     countryList: COUNTRY_LIST,
     selectedCountries: COUNTRY_LIST
     };
    wrapper.update();
    expect(filtersReducer(initialState, { type: 'FETCH_COUNTRY_LIST' })).toEqual(...initialState, expectedState);
   });

});

Test Results :
Expected value to equal:
  {"countryList": [{"checked": false, "name": "United States", "value": "USA"}, {"checked": false, "name": "United Kingdom", "value": "GBR"}, {"checked": false, "name": "India", "value": "IND"}, {"checked": false, "name": "Singapore", "value": "SNG"}, {"checked": false, "name": "Japan", "value": "JPN"}, {"checked": false, "name": "South Africa", "value": "ZAF"}, {"checked": false, "name": "Germany", "value": "DEU"}, {"checked": false, "name": "China", "value": "CHN"}, {"checked": false, "name": "France", "value": "FRA"}], "selectedCountries": [{"checked": false, "name": "United States", "value": "USA"}, {"checked": false, "name": "United Kingdom", "value": "GBR"}, {"checked": false, "name": "India", "value": "IND"}, {"checked": false, "name": "Singapore", "value": "SNG"}, {"checked": false, "name": "Japan", "value": "JPN"}, {"checked": false, "name": "South Africa", "value": "ZAF"}, {"checked": false, "name": "Germany", "value": "DEU"}, {"checked": false, "name": "China", "value": "CHN"}, {"checked": false, "name": "France", "value": "FRA"}]}
Received:
  {"countryList": **undefined**, "isAllSelected": false, "isAllSelectedR": false, "isAllSelectedS": false, "regionList": [], "sectorList": [], "selectedCountries": **undefined**, "selectedRegions": [], "selectedSectors": []}

Это код моего Магазина:

import { createStore, applyMiddleware } from 'redux';
import { composeWithDevTools } from 'redux-devtools-extension'
import rootReducer from '../reducers/rootReducer'
import gridQueryMiddleware from "../services/gridQueryMiddleware";

export const configureStore = (preloadedState) => {
  const middlewares = [gridQueryMiddleware];
  const middlewareEnhancer = applyMiddleware(...middlewares);

  const storeEnhancers = [middlewareEnhancer];

  const composedEnhancer  = composeWithDevTools(...storeEnhancers);

  const store = createStore(
    rootReducer,
    preloadedState,
    composedEnhancer
  );

  if (process.env.NODE_ENV !== 'production') {
    if (module.hot) {
      module.hot.accept('./reducers/rootReducer', () => {
        const newRootReducer = require('./reducers/rootReducer').default;
        store.replaceReducer(newRootReducer)
      })
    }
  }

  return store;
};
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...