我按照redux.org的基本示例测试异步操作
action.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)
})
}
}
test.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
打开网址: http://localhost:5051/webpack-dev-server/
nock
设置中有一个尾随的/
。请改为使用nock('http://example.com')
而不是nock('http://example.com/')
:) - Mario Tacke