Testing action creators

Action creators are pretty easy to test. We already explored what action creators are and how to use them in Chapter 1, Understanding Redux. As a reminder, in Redux, action creators are simply functions that return plain objects. Nothing complicated, right? Let's consider an action creator from our health application. We just made a function called addNewDoctor that takes new doctor data and returns the plain object, as follows:

export function addNewDoctor(newDoctorData) {
return {
type: "ADD_NEW_DOCTOR",
newDoctorData
};
}

Let's test our action creators, as follows:

import * as actions from "../actionCreators";
describe("actions", () => {
it("should create an action to add a doctor", () => {
const newDoctorData = {
name: "Dr. Yoshmi Mukhiya",
email: "[email protected]",
age: 22
};
const expectedAction = {
type: "ADD_NEW_DOCTOR",
newDoctorData
};
expect(actions.addNewDoctor(newDoctorData)).toEqual(expectedAction);
});
});

Getting the hang of it? It is easy, right? You just import your function and give it the required arguments. Then, you assert that the function returns the correct object. It's not rocket science.

If you remember, in Chapter 1Understanding Redux, we defined actions for authentication and deauthentication. The snippet looked as follows:

export const authenticate = (credentials: Credentials) => ({
type: "AUTHENTICATE",
payload: credentials
});
export const deauthenticate = () => ({
type: "DEAUTHENTICATE"
});

Writing tests for actions is straightforward. Let's go ahead and write the test, as follows:

import { authenticate, deauthenticate } from '../auth'
describe('actions/authenticate', () => {
it('should return action object correctly', () => {
const credentials = {
email: ‘[email protected]’,
password: mentalhelse,
}
expect(authenticate(credentials)).toEqual({
type: 'AUTHENTICATE',
payload: credentials,
})
})
})
describe
('actions/deauthenticate', () => {
it('should return action object correctly', () => {
expect(deauthenticate()).toEqual({
type: 'DEAUTHENTICATE',
})
})
})
..................Content has been hidden....................

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