0

I'm new to testing so I'm not even sure if this is something I'm 'supposed' to be testing, but here goes:

I'm following the example in https://github.com/reactjs/redux/blob/master/docs/recipes/WritingTests.md for how to write a test for an async action creator. Here is the code I'm testing:

export function receiveRepresentatives(json) {
  return {
    type: RECEIVE_REPRESENTATIVES,
    representatives: json.objects
  }
}

export function getRepresentatives (zipcode) {
  return dispatch => {
    dispatch(changeFetching())
    return fetch('/api/representatives' + zipcode)
        .then(response => response.json())
        .then(json => dispatch(receiveRepresentatives(json))) 
  }
}

My testing framework is mocha/chai with nock and configureMockStore. I want to mock my call to /api/representative with nock but I can't figure out how.

const middlewares = [ thunk ]
const mockStore = configureMockStore(middlewares)

describe('async actions', () => {
  afterEach(() => {
    nock.cleanAll()
  })

  it('creates RECEIVE_REPRESENTATIVES when fetching representatives has been done', (done) => {
    nock('http://localhost')
      .get('/api/representatives')
      .reply('200', { objects: { name: 'Barbara Lee'} } )

    const expectedActions = [
      { type: RECEIVE_REPRESENTATIVES, representatives: { objects: { name: 'Barbara Lee'} } }
    ]

    const store = mockStore({}, expectedActions, done)
    store.dispatch(getRepresentatives(94611))
      .then(() => {
        const actions = store.getActions()
        expect(actions[0].type).toEqual(receiveRepresentatives())

        done()
      })
  })
})

0 Answers0