我按照 redux.org 的基本示例来测试异步操作
动作.js
我的代码是这样的:
import axios from 'axios'
export function getGoodDataStart(){
return{
type: "GOOD_DATA_START"
}
}
export function getGoodDataSuccess(payload){
console.log('success', payload)
return {
type: "GOOD_DATA_SUCCESS",
payload: payload
}
}
export function getGoodDataFail(){
return{
type: "GOOD_DATA_FAIL"
}
}
export function getGoodData(){
return (dispatch) => {
dispatch( getGoodDataStart() )
return axios.get('http://www.google.com/list')
.then( response => {
console.log('fake res',response)
dispatch(getGoodDataSuccess (response) )
})
.catch( err => {
console.log('fake err',err)
})
}
}
测试.js
import nock from 'nock'
import React from 'react'
import {expect} from 'chai'
import {getGoodData} from 'registerAction'
import configureMockStore from 'redux-mock-store'
import thunk from 'redux-thunk'
const middlewares = [ thunk ]
const mockStore = configureMockStore(middlewares)
describe('Register component', () => {
it('async action', function () {
nock('http://www.google.com')
.get('/list')
.reply(200,'ok!' )
const store = mockStore({
myData: '' ,
})
const expected = [
{type: "GOOD_DATA_START"},
{type: "GOOD_DATA_SUCCESS", payload: 'ok!'}
]
return store.dispatch(getGoodData())
.then( () => {
expect(store.getActions()).to.equal(expected)
})
})
})
我遇到的问题是,nock 没有阻止请求,它让函数 getGoodData 向 google.com 发出真正的请求。我究竟做错了什么?
错误的屏幕截图:
这是演示:https ://github.com/craigcosmo/react-redux-test
安装:npm i
测试: npm run test