Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #### Store setup
- ```js
- import { createStore } from 'redux';
- const storeFactory = (stateOverrides) => createStore(rootReducer, _.merge({}, initialState, stateOverrides), middleware);
- ```
- #### Wait for API calls to complete
- Listen to store events.
- ```js
- const waitForAction = (targetStore, conditionFn, timeout = 2000) =>
- new Promise((resolve, reject) => {
- const unsubscribe = targetStore.subscribe(() => {
- const state = targetStore.getState();
- if (conditionFn(state)) {
- unsubscribe();
- resolve(state);
- }
- setTimeout(() => {
- unsubscribe();
- reject(`No action found after ${timeout / 1000}sec`);
- }, timeout);
- });
- });
- ```
- #### Component setup for testing
- ```js
- import { Provider } from 'react-redux';
- import { mount } from 'enzyme';
- const setup = (Component, extraProps = {}, state = {}, renderer = mount) => {
- const store = storeFactory(state);
- const wrapper = renderer(
- <Provider store={store}>
- <Component {...extraProps} />
- </Provider>
- );
- return {
- wrapper,
- store,
- };
- };
- ```
- #### Sample test
- ```js
- import MyComponent from '/path/to/component';
- describe('<MyComponent/>', () => {
- before(() => {
- fetchMock.get('/some-service/api/v1/some-entity', {
- ok: true,
- content: [/*some data*/],
- });
- });
- it('render succesfully', async () => {
- const {wrapper, store} = setup(MyComponent, customProps, initialStateOverrides);
- // wait till the store's state is updated with items received from the mocked API
- await waitForAction(store, (state) => state.allItem.length > 0);
- const foundItems = wrapper.find('Items');
- expeect(foundItems.length).to.eql(3);
- // ... more expectations
- });
- });
- ```
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement