【问题标题】:how to test react-saga axios post如何测试 react-saga axios post
【发布时间】:2018-01-23 14:28:25
【问题描述】:

我正在学习如何测试并使用一些示例作为指导,我正在尝试模拟登录帖子。该示例使用 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
    })
  })
})

【问题讨论】:

  • 发电机是如何工作的?
  • 第一次使用,还在学习中

标签: javascript reactjs jestjs chai nock


【解决方案1】:

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

要解决此问题,您要么必须删除 nock 设置中的指定正文,要么使用凭据调度 LOGIN_REQUEST 操作,并更改指定正文以匹配您设置为 payload 的编码凭据。

【讨论】:

  • 我从 nock 中删除了凭据,但仍然出现同样的错误
【解决方案2】:

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

【讨论】:

  • 这个答案是否解决了问题?目前尚不清楚您应该在哪里调用 done()。以这种方式调用可能会过早返回 done()。
  • 当您没有在测试中返回承诺时,您应该手动调用 done()。
猜你喜欢
  • 1970-01-01
  • 2019-02-25
  • 2021-06-04
  • 1970-01-01
  • 2018-06-10
  • 1970-01-01
  • 2019-05-18
  • 2023-04-06
  • 1970-01-01
相关资源
最近更新 更多