10

我正在学习如何测试并使用一些示例作为我试图模拟登录帖子的指南。该示例使用 fetch 进行 http 调用,但我使用 axios。这是我得到的错误

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

此错误的所有答案都与 fetch 有关,我如何使用 axios 执行此操作

./传奇

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

./登录测试

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
    })
  })
})
4

2 回答 2

2

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

于 2017-08-21T22:39:32.867 回答
1

由于您在模拟中指定了正文( { userName: 'xxx@xxx.com', password: 'xxxxx' }) ,因此在收到带有给定 URL 和正文的发布请求之前nock,它不会响应。loginReply但是您没有发送credentials您的LOGIN_REQUEST操作,因此您的 axios 请求正文(payload.data)总是为空的。这就是为什么您的nock模拟不会在指定的异步超时内回复并jest给出此超时错误的原因。

要解决此问题,您要么必须在设置中删除指定的主体,nock要么使用凭据发送LOGIN_REQUEST操作并更改指定的主体以匹配您设置为的编码凭据payload

于 2017-08-20T17:30:52.587 回答