jeudi 25 mai 2017

Testing promises within promises

I used to have the following code:

api.postUser(userInfo).then(response => {
  utils.redirect(response.url);
})

And I was able to write a test that looked like this:

const successPromise = Promise.resolve({ url: 'successUrl' })

beforeEach(function() {
  sinon.stub(api.postUser).returns(successPromise);
}

afterEach(function() {
  api.postUser.restore();
}

it "calls API properly and redirects" do  
  expect(api.postUser).calledWith(userInfo).toBe(true);
  successPromise.then(() => {
    expect(utils.redirect.calledWith('successUrl')).toBe(true);
    done();
  }
emd

And everything was green.

Now, I had to add another promise to make another external call, before doing the api postUser call, so my code looks like this:

fetchUserData(names).then(userData => {
  api.postUser(userData).then(response => {
   utils.redirect(response.url);
  })
})

where fetchUseData is a chain of many promises, such like:

function fetchNames(names) {
  // some name regions
  return Promise.all(names);
}
function fetchUserData(names) {
  fetchUsersByNames(names).then(users => {
    // For now we just choose first user
    {
      id: users[0].id,
      name: users[0].name,
    }
  });
}

And the tests I had fail. I am trying to understand how to change my tests to make sure that I am still testing that I do the final API call properly and the redirect is also done. I want to stub what fetchUserData(names), to prevent doing that HTTP call.

Aucun commentaire:

Enregistrer un commentaire