Day Five: Building and Testing Redux Actions

For today, I started working on the actions file with redux’s own action documentation as reference. It seems their sample tend to favor seperating actions types and action creators into different files, but I think I favor keeping them one file for now so it is easier for me to keep track of things. I only have 3 actions types and 4 action creator for now anyway.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/* action types*/
export const FETCH_REQUEST = 'FETCH_REQUEST'
export const FETCH_SUCCESS = 'FETCH_SUCCESS'
export const FETCH_FAILURE = 'FETCH_FAILURE'

/* action creators*/
export function fetchRequest() {
  return {
    type: FETCH_REQUEST
  }
}

export function fetchSuccess(body) {
  return {
    type: FETCH_SUCCESS,
    body
  }
}

export function fetchFailure(err) {
  return {
    type: FETCH_FAILURE,
    err
  }
}

fetchJSON action creator, posted as image because ${} escapes the code snippet display

I also using redux’s Writing Tests doc, so the action creators are tested. I didn’t work on the fetchJSON() one though, because there is a fetch() there, making the action create async. The doc do have a section for async action creator, but I think I will do that next.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
describe('actions.js: ', () => {
  it('should create an action to fetch request', () => {
    const requestAction = {
      type: 'FETCH_REQUEST',
    }
    expect(actions.fetchRequest()).to.eql(requestAction)
  });
  it('should create an action for successful request', () => {
    const body = 'Fetch successful';
    const successAction = {
      type: 'FETCH_SUCCESS',
      body
    }
    expect(actions.fetchSuccess(body)).to.eql(successAction)
  });
  it('should create an action for failed request', () => {
    const err = 'Fetch failed';
    const failureAction = {
      type: 'FETCH_FAILURE',
      err
    }
    expect(actions.fetchFailure(err)).to.eql(failureAction)
  });
})

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.