1

Suppose I have an API that return user detail: /api/get_user/1

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

And a "main function" like this:

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
}

For testing the "ACTION" source, I can simply made an 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()
    }
  })

})

The question is. Is it possible to do the same thing (using plan xstream observable) to test cycle-http driver without a helper from something like nock? Or is there a better way to test something like this?

4

1 回答 1

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

于 2017-03-27T07:43:46.543 回答