Testing a standard action

We will need an action to notify Redux that we have the speakers after they have been loaded. There is no reason why we can't start there. So, let's write a test for the successful retrieval of speakers.

import { expect } from 'chai';

describe('Speaker Actions', () => {
describe('Sync Actions', () => {
describe('Get Speakers Success', () => {
it('exists', () => {
expect(getSpeakersSuccess).to.exist;
});
});
});
});

Running this test should fail. To make the test pass, define a function named getSpeakersSuccess.

function getSpeakersSuccess() {
}

Because of the simplicity of a typical action, our next test will essentially test the functionality of the action. We could break this into multiple tests, but all we are really doing is asserting on the structure of the data returned. Concerning the single assert rule, we are still only asserting one thing.

it('is created with correct data', () => {
// arrange
const speakers = [{
id: 'test-speaker',
firstName: 'Test',
lastName: 'Speaker'
}];

// act
const result = getSpeakersSuccess(speakers);

// assert
expect(result.type).to.equal(GET_SPEAKERS_SUCCESS);
expect(result.speakers).to.have.lengthOf(1);
expect(result.speakers).to.deep.equal(speakers);
});

To make this test pass, we need to make significant changes to our current implementation of the getSpeakersSuccess function.

const GET_SPEAKERS_SUCCESS = 'GET_SPEAKERS_SUCCESS';

function getSpeakersSuccess(speakers) {
return { type: GET_SPEAKERS_SUCCESS, speakers: speakers };
}

In Redux, actions have an expected format. They must contain a type property and usually contain some data structure. In the case of getSpeakersSuccess, our type is a constant, GET_SPEAKERS_SUCCESS, and the data is an array of speakers passed into the action. To make them available to the application, let's move the action and the constant into their own files. We need a speakerActions file and an actionTypes file,

src/actions/speakerActions.js:

import * as types from '../reducers/actionTypes';

export function getSpeakersSuccess(speakers) {
return { type: types.GET_SPEAKERS_SUCCESS, speakers: speakers };
}

src/reducers/actionTypes.js:

export const GET_SPEAKERS_SUCCESS = 'GET_SPEAKERS_SUCCESS';

Add import statements to the test and all the tests should pass. For a typical action, this is the format for testing. The placement of the action types in the reducers folder is for dependency inversion reasons. From a SOLID standpoint, the reducers are defining a contract of interaction, which is represented by the action types. The actions are fulfilling that contract.

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

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