jeudi 24 août 2017

how to test redx-saga fetchApi has if and else

I have such a problem in the test, as follows:

Is my test code to write a problem, or business logic to achieve it properly? Run test is fail, beacause has if else about api return res in sagas.js. if res.r === 0 set load_success, and else set load_fail; and has try catch block;

fetch api code:

const API_URL = 'xxx'
export const fetchLoadPage = (query) => {
  return Fetch.get(
    API_URL,
    query
  ).then(res => { return res })
  .catch(err => { return err })
}

sagas.js

export function* loadPage() {
  try {
    const res = yield call(fetchLoadPage)
    let r = parseInt(res.r, 10)
    let error = res.error
    let msg = error || 'load fail'
    if (r === 0) {
      return yield put({ type: types.LOAD_PAGE_SUCCESS, res })
    } else {
      return yield put({ type: types.LOAD_PAGE_FAIL, msg })
    }
  } catch (err) {
    let msg = err || 'load fail'
    return yield put({ type: types.LOAD_PAGE_FAIL, msg })
  }
}

test

test('page:saga:loadPage', t => {
  const generator = loadPage()
  const res = {
    r: 0,
    data: []
  }

  t.deepEqual(
    generator.next().value,
    call(fetchLoadPage),
    'must xxx'
  )

  t.deepEqual(
    generator.next().value,
    put({type: types.LOAD_PAGE_SUCCESS, res}),
    'must xxx'
  )

  t.ok(generator.next().done, 'must finish')
  t.end()
})

Aucun commentaire:

Enregistrer un commentaire