The Get All Speakers reducer

Now that we have tested the actions related to getting all the speakers, it's time to move on to testing the reducers. As usual, let's begin with an exists test.

describe('Speaker Reducers', () => {
describe('Speakers Reducer', () => {
it('exists', () => {
expect(speakersReducer).to.exist;
});
});
});

To make this test pass, all we need to do is define a function named speakersReducer.

function speakersReducer() {
}

Our next test will check the functionality of the reducer.

it('Loads Speakers', () => {
// arrange
const initialState = [];

const speaker = {
id: 'test-speaker',
firstName: 'Test',
lastName: 'Speaker'
};
const action = actions.getSpeakersSuccess([speaker]);

// act
const newState = speakersReducer(initialState, action);

// assert
expect(newState).to.have.lengthOf(1);
expect(newState[0]).to.deep.equal(speaker);
});

This test is larger than we normally prefer, so let's walk through it. In the arrange, we configure the initial state and create an action result consisting of an array of a single speaker. When a reducer is called, the previous state of the application and the result of action are passed to it. In this case, we start with an empty array and the modification is the addition of a single speaker.

Next, in the Act section of the test, we call the reducer passing in the initialState and the result of our action call. The reducer returns a new state for us to use in the application.

Lastly, in the assert, we expect that the new state consists of a single speaker and that the speaker has the same data as the speaker we created for the action.

To make the test pass we need to handle the action being passed into the reducer.

function speakersReducer(state = [], action) {
switch(action.type) {
case types.GET_SPEAKERS_SUCCESS:
return action.speakers;
default:
return state;
}
}

Because, in an application using Redux, reducers are called for every action, we need to determine what to do for any action that is not the action we want to handle. The proper response in those cases is to simply return the state with no modification.

For the action type that we do want to handle, in this case, we are returning the actions speakers array. In other reducers, we might combine the initial state with the actions result, but for get speakers success we want to replace the state with the value we receive.

The last step, now that all our tests are passing, is to extract the speaker reducer from the test file and move it to speakerReducer.js

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.224.73.227