gaearon / ama

Ask me anything!
222 stars 5 forks source link

Do you have any prefer ways to test a function that use many promises? #49

Closed chentsulin closed 9 years ago

chentsulin commented 9 years ago

I always feel painful when test something like this:

import 'isomorphic-fetch';
import { normalize } from 'normalizr';
import { camelizeKeys } from 'humps';

export function callGetApi(endpoint, schema) {
  return fetch(endpoint)
    .then(response => {
      return response.json().then(json => ({ json, response }));
    })
    .then(({ json, response }) => {
      if (!response.ok) {
        return Promise.reject(json);
      }
      const camelizedJson = camelizeKeys(json);

      return normalize(camelizedJson, schema);
    });
}

I see you also suggest using mocha as test engine in redux. Do you have any prefer ways or examples to test a function like this? Unit test with some mocks & stubs or any other ways?

Thanks

gaearon commented 9 years ago

It depends on what behavior you would like to test.

chentsulin commented 9 years ago

When I implement a module something like api middleware in redux real world example, I found I don't really know how to well test it. Then I split it into middleware, api utils, schemas three files and try to follow single responsibility principle.

Maybe I Just want to avoid introducing some stupid bugs when I modified some code. I usually mock third party libraries in unit tests and then test they have been called correctly, but it seems cumbersome when a lot of .then call. Hope to hear some your advice or your past experience here.

gaearon commented 9 years ago

I'd just mock fetch and verify that different API responses handled in different order produce a state that makes sense. If I needed to test something more specific, I'd split the function and test its parts separately.