有点难过这一件事。按照Redux文档为我的异步操作(docs here)设置测试后,出现错误:
动作可能不是未定义的。 (在调度时(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({})
}
}
最佳答案
有known issue带有axios
嘲笑nock
请求。因此,我相信您的fetchTransactions
动作创建者中的Promise链属于catch
子句。请检查您的handleErr
函数,它是否返回有效的操作?我敢打赌它返回undefined
,这就是为什么您有此错误消息。
关于unit-testing - 错误:在带有nock和模拟存储的Redux应用程序中的异步操作测试中,操作可能未定义,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42961512/