【问题标题】:How to test cyclejs http driver?如何测试cyclejs http驱动程序?
【发布时间】:2017-03-27 06:21:27
【问题描述】:

假设我有一个返回用户详细信息的 API: /api/get_user/1

{
  "status": 200,
  "data": {
    "username": "username1",
    "email": "username@email.com"
  }
}

还有一个像这样的“主要功能”:

function main (sources) {
  const request$ = sources.ACTIONS
    .filter(action => action.type === 'GET_USER_REQUEST')
    .map(action => action.payload)
    .map(payload => ({
      category: 'GET_USER_REQUEST',
      url: `${BASE_URL}/api/get_user/${payload.userId}`,
      method: 'GET'
    }))

  const action$ = sources.HTTP
    .select('GET_USER_REQUEST')
    .flatten()
    .map(response => response.data)

  const sinks = {
    HTTP: request$,
    LOG: action$
  }
  return sinks
}

为了测试“ACTION”源,我可以简单地制作一个 xstream observable

test.cb('Test main function', t => {

  const actionStream$ = xs.of({
    type: 'GET_USER_REQUEST',
    payload: { userId: 1 }
  })
  const sources = { ACTION: actionStream$ }
  const expectedResult = {
    category: 'GET_USER_REQUEST',
    url: `${BASE_URL}/api/get_user/${payload.userId}`,
    method: 'GET'
  }

  main(sources).HTTP.addEventListener({
    next: (data) => {
      t.deepEqual(data, expectedResult)
    },
    error: (error) => {
      t.fail(error)
    },
    complete: () => {
      t.end()
    }
  })

})

问题是。是否可以做同样的事情(使用plan xstream observable) 在没有像 nock 这样的助手的情况下测试 cycle-http 驱动程序? 或者有没有更好的方法来测试这样的东西?

【问题讨论】:

    标签: http testing cyclejs


    【解决方案1】:

    您可以像这样模拟 HTTP 源:

    test.cb('Test main function', t => {
      const actionStream$ = xs.of({
        type: 'GET_USER_REQUEST',
        payload: { userId: 1 }
      })
    
      const response$ = xs.of({
        data: {
          status: 200,
          data: {
            username: "username1",
            email: "username@email.com"
          }
        }
      });
    
      const HTTP = {
        select (category) {
          // if you have multiple categories you could return different streams depending on the category
          return xs.of(response$);
        }
      }
    
      const sources = { ACTION: actionStream$, HTTP }
    
      const expectedResult = {
        category: 'GET_USER_REQUEST',
        url: `${BASE_URL}/api/get_user/${payload.userId}`,
        method: 'GET'
      }
    
      main(sources).HTTP.addEventListener({
        next: (data) => {
          t.deepEqual(data, expectedResult)
        },
        error: (error) => {
          t.fail(error)
        },
        complete: () => {
          t.end()
        }
      })
    
    })
    

    真的,我们应该有一个mockHTTPSource 帮助器来使这更容易一些。我已经为此打开了一个问题。 https://github.com/cyclejs/cyclejs/issues/567

    如果您想测试某些事情是否在正确的时间发生,您可以将此模式与@cycle/time 结合使用。

    http://github.com/cyclejs/time

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-10
      • 2019-08-22
      • 1970-01-01
      • 2012-09-02
      相关资源
      最近更新 更多