我想在我的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()请求?