0

我是测试新手,所以我什至不确定这是否是我“应该”要测试的东西,但这里有:

我正在关注https://github.com/reactjs/redux/blob/master/docs/recipes/WritingTests.md中的示例,了解如何为异步操作创建者编写测试。这是我正在测试的代码:

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))) 
  }
}

我的测试框架是 mocha/chai,带有 nock 和 configureMockStore。我想用 nock 模拟我对 /api/representative 的调用,但我不知道怎么做。

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()
      })
  })
})
4

0 回答 0