晚上好,我在refatorei之后无法测试自己的传奇,原来的格式是
export function* getUser(axios){
try {
const user = yield call(axios.get, 'http://')
if(user.data.error){
return yield put(ActionsCreators.getUserFailure(user.data.message))
}
yield put(ActionsCreators.getUserSuccess(user.data.data))
} catch (error) {
yield put(ActionsCreators.getUserFailure(error.message))
}
}
redux-saga-testing
测试看起来像这样。
test('with redux saga testing', () => {
const axiosMock = {
get: jest.fn()
}
const it = sagaHelper(getUser(axiosMock))
it('should return ', result => {
expect(result).toEqual(call(axiosMock.get, 'http://'))
})
})
然后我重构了这种格式。
service.js
import axios from 'axios'
const Api = base => {
const client = axios.create({
baseURL: base
})
const getAuthHeader = () => {
const token = localStorage.getItem('token')
return {
headers: {
Authorization: 'Bearer '+token
}
}
}
const get = (endpoint) => client.get(endpoint, getAuthHeader())
return {
auth: () => get('api/current')
}
}
export default Api
rootSaga
import Api from '../services/API'
import { getUser } from './auth'
const api = new Api(baseURL)
yield all([
takeLatest(Types.GET_USER_REQUEST, getUser({ api }))
])
传奇
export const getUser = ({ api }) => function*(){
try {
const user = yield call(api.auth)
if(user.data.error){
return yield put(ActionsCreators.getUserFailure(user.data.message))
}
yield put(ActionsCreators.getUserSuccess(user.data.data))
} catch (error) {
yield put(ActionsCreators.getUserFailure(error.message))
}
}
以这样的形式,我向api注入了getuser,并且调用接收到api并调用了服务,这时我无法再测试我的传奇了,我想检查api是否在调用正确的url,但我不知道该如何期待,已经测试过模拟和api并在getuser中注入但没有成功。谁能给我一个关于如何使用这种注入依赖性执行saga测试的秘密经验。