1

我有一个要在我的 React/Redux 应用程序中测试的操作:

export const SET_SUBSCRIBED = 'SET_SUBSCRIBED'

export const setSubscribed = (subscribed) => {
  // return {
  //   type: SET_SUBSCRIBED,
  //   subscribed: subscribed
  // }

  return function(dispatch) {
    var url = "https://api.github.com/users/1/repos";

    return fetch(url)
      .then(function(result) {
        if (result.status === 200) {
          dispatch({
            type: SET_SUBSCRIBED,
            subscribed: subscribed
          })
          return result
        }

        return 'failed' //todo
      })
  }
}

这是我的测试:

import { setSubscribed } from '../actions/subscriptions'
import nock from 'nock'
import configureMockStore from 'redux-mock-store'
import thunk from 'redux-thunk'
import * as actions from '../actions/subscriptions'

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

describe('Action::Subscriptions', () => {
  describe('#setSubscribed()', () => {
    afterEach(() => {
      nock.cleanAll()
    })

    describe('when subscribed is true', () => {
      beforeEach(() =>{
        nock('https://api.github.com/')
          .get('/users/1/repos')
          .reply(200, 'yes')

      })

      it('returns SET_SUBSCRIBED type and subscribed true', () => {
        const store = mockStore({ subscribed: false })

        return store.dispatch(actions.setSubscribed(true))
          .then(() => {
            expect(store.getActions()).toEqual([{type: 'SET_SUBSCRIBED', subscribed: true}])
          })
      })
    })
  })
})

当我运行测试时,我不断收到错误:

TypeError: Network request failed

看起来我的测试对 nock 不太满意。

我做错了什么以及如何成功存根 fetch() 请求?

4

0 回答 0