如何测试react-saga axios post

tex*_*697 10 javascript chai reactjs jestjs nock

我正在学习如何测试并使用一些示例作为指导我试图模拟登录帖子.该示例使用了对http调用的提取,但我使用的是axios.这是我得到的错误

超时 - 在jasmine.DEFAULT_TIMEOUT_INTERVAL指定的超时内未调用异步回调

这个错误的所有答案都与fetch有关,我如何用axios做到这一点

./saga

const encoder = credentials => Object.keys(credentials).map(key => `${encodeURIComponent(key)}=${encodeURIComponent(credentials[key])}`).join('&')

const postLogin = credentials => {
  credentials.grant_type = 'password'
  const payload = {
    method: 'post',
    headers: config.LOGIN_HEADERS,
    data: encoder(credentials),
    url: `${config.IDENTITY_URL}/Token`
  }
  return axios(payload)
}

function * loginRequest (action) {
  try {
    const res = yield call(postLogin, action.credentials)
    utils.storeSessionData(res.data)
    yield put({ type: types.LOGIN_SUCCESS, data: res.data })
  } catch (err) {
    yield put({ type: types.LOGIN_FAILURE, err })
  }
}

function * loginSaga () {
  yield takeLatest(types.LOGIN_REQUEST, loginRequest)
}

export default loginSaga
Run Code Online (Sandbox Code Playgroud)

./login-test

const loginReply = {
  isAuthenticating: false,
  isAuthenticated: true,
  email: 'foo@yahoo.com',
  token: 'access-token',
  userId: '1234F56',
  name: 'Jane Doe',
  title: 'Tester',
  phoneNumber: '123-456-7890',
  picture: 'pic-url',
  marketIds: [1, 2, 3]
}

describe('login-saga', () => {
  it('login identity user', async (done) => {
    // Setup Nock
    nock(config.IDENTITY_URL)
      .post('/Token', { userName: 'xxx@xxx.com', password: 'xxxxx' })
      .reply(200, loginReply)

    // Start up the saga tester
    const sagaTester = new SagaTester({})

    sagaTester.start(loginSaga)

    // Dispatch the event to start the saga
    sagaTester.dispatch({type: types.LOGIN_REQUEST})

    // Hook into the success action
    await sagaTester.waitFor(types.LOGIN_SUCCESS)

    // Check the resulting action
    expect(sagaTester.getLatestCalledAction()).to.deep.equal({
      type: types.LOGIN_SUCCESS,
      payload: loginReply
    })
  })
})
Run Code Online (Sandbox Code Playgroud)

soc*_*bot 2

您收到以下错误:Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL因为您没有done在测试中调用回调。