我正在使用redux-saga
来按如下方式获取api:
// getTodoListSaga.js
import { call, put, takeLatest } from 'redux-saga/effects'
import { create } from 'apisauce'
export const API = create({
baseURL: `http://localhost:4000`,
headers: {
'Content-Type': 'application/json'
}
})
function* getTodoList() {
try {
const response = yield call(() => API.get(`/todos`))
if (response.ok) {
yield put({
type: 'GET_TODOS_SUCCESS',
data: response.data
})
} else {
yield put({
type: 'GET_TODOS_FAILED'
})
}
} catch (errors) {
yield put({
type: 'GET_TODOS_FAILED'
})
}
}
function* getTodoListSaga() {
yield takeLatest('GET_TODOS_REQUEST', getTodoList)
}
export default getTodoListSaga
我尝试应用redux-saga-test-plan对其进行如下测试:
// __tests__/getTodoListSaga.test.js
import { call } from 'redux-saga/effects'
import MockAdapter from 'axios-mock-adapter'
import { expectSaga } from 'redux-saga-test-plan'
import getTodoListSaga, { API } from '../getTodoListSaga'
const API_URL = 'http://localhost:4000'
describe('getTodoList saga test', () => {
it('Test fetch Todos success', () => {
const todos = [
{ id: 1, todo: 'Go shopping' },
{ id: 2, todo: 'Go Camping' }
]
const mock = new MockAdapter(API.axiosInstance)
mock.onGet(`${API_URL}/todos`).reply(200, todos)
const getTodos = () => API.get(`${API_URL}/todos`)
return expectSaga(getTodoListSaga)
.provide([[call(() => getTodos), { response: { ok: true, data: todos }}]])
.put({ type: 'GET_TODOS_SUCCESS', data: todos })
.dispatch({ type: 'GET_TODOS_REQUEST' })
.silentRun()
})
it('Test fetch Todos fail', () => {
const error = 404
const mock = new MockAdapter(API.axiosInstance)
mock.onGet(`${API_URL}/todos`).reply(error)
const getTodos = () => API.get(`${API_URL}/todos`)
return expectSaga(getTodoListSaga)
.provide([[call(() => getTodos), error]])
.put({ type: 'GET_TODOS_FAILED' })
.dispatch({ type: 'GET_TODOS_REQUEST' })
.silentRun()
})
})
但是我不知道如何测试catch块以覆盖100%的代码行。有人帮我吗?