[英]Error: Action may not be undefined in async action testing in Redux app with nock and mock-store
有點難過這一件事。 按照Redux文檔為我的異步操作( docs此處 )設置測試后,出現錯誤:
動作可能不是未定義的。 (在調度時(node_modules / redux-mock-store / lib / index.js:35:19))
測試此操作:
export const FETCH_TRANSACTIONS = 'FETCH_TRANSACTIONS'
function fetchTransactionsSuccess (transactions) {
return {
type: FETCH_TRANSACTIONS,
payload: transactions
}
}
export const fetchTransactions = () => dispatch => axios.get('/api/transactions')
.then(transactions => dispatch(fetchTransactionsSuccess(transactions)))
.catch(err => dispatch(handleErr(err)))
這就是測試本身。 任何幫助都將是驚人的。 凝視了這么久,我的眼睛受傷了。
import configureMockStore from 'redux-mock-store'
import thunk from 'redux-thunk'
import * as actions from '../../client/actions/actionCreators'
import nock from 'nock'
import expect from 'expect'
const middlewares = [ thunk ]
const mockStore = configureMockStore(middlewares)
describe('async actions', () => {
afterEach(() => {
nock.cleanAll()
})
it('dispatches FETCH_TRANSACTIONS when data is returned', () => {
nock('http://localhost:3000/')
.get('/api/transactions')
.reply(200, [
{
"_id": "588900efdf9d3e0905a2d604",
"amount": 4.50,
"name": "Cashew Nuts",
"__v": 0,
"date": "2017-01-25T00:00:00.000Z",
"user": "58c2a33cc6cd5a5d15a8fc0c"
},
{
"_id": "58890108df9d3e0905a2d605",
"amount": 6.25,
"name": "Monmouth Coffee",
"__v": 0,
"date": "2017-01-25T00:00:00.000Z",
"user": "58c2a33cc6cd5a5d15a8fc0c"
}
])
const expectedActions = [
{
type: actions.FETCH_TRANSACTIONS,
payload: [
{
"_id": "588900efdf9d3e0905a2d604",
"amount": 4.50,
"name": "Cashew Nuts",
"__v": 0,
"date": "2017-01-25T00:00:00.000Z",
"user": "58c2a33cc6cd5a5d15a8fc0c"
},
{
"_id": "58890108df9d3e0905a2d605",
"amount": 6.25,
"name": "Monmouth Coffee",
"__v": 0,
"date": "2017-01-25T00:00:00.000Z",
"user": "58c2a33cc6cd5a5d15a8fc0c"
}
]
}
]
const store = mockStore({ transactions: [] })
console.log(actions)
return store.dispatch(actions.fetchTransactions())
.then(() => {
expect(store.getActions()).toEqual(expectedActions)
})
})
})
更新handleErr函數返回setCurrentUser,這是另一個動作(原始動作通過dispatch調用:
export function handleErr (err) {
if (err.status === 401 || err.status === 404) {
localStorage.removeItem('mm-jwtToken')
setAuthToken(false)
return setCurrentUser({})
}
}
使用nock
axios
請求存在一個已知問題 。 因此,我相信您的fetchTransactions
動作創建者中的promise鏈屬於catch
子句。 請檢查您的handleErr
函數,它是否返回有效的Action? 我敢打賭它返回undefined
,這就是為什么您有此錯誤消息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.