patentul patentul - 5 months ago 43
Node.js Question

Unit testing promises from an api using Jasmine

I wrote an API that is promised based. Which is the best way to unit test it? Is Jasmine a good approach?

Also can on give me an example on how one can unit test promises? Should one unit test also the "then" and also the "catch" part?

Answer

Jasmine is definitely a strong choice for doing promise based unit testing. Without knowing too much about your API, below are a few examples of how you can do unit testing while waiting for promise resolution or failure.

The keyword in the sample below is the done variable passed in to each of the unit tests (it blocks). This lets jasmine know that the test is asynchronous and jasmine will wait for the done function to be called before moving on from that unit test.

Hope this helps!

describe('Unit tests', function() {
  it('promise should succeed', function (done) {
    myApi.function().then(function(data) {
      //assert data came back correctly
      done();
    }).catch(function() {
      fail();
    });
  });

  it('promise should throw error', function() {
    myApi.function().then(function(data) {
      fail();
    }).catch(function(error) {
      //assert error has been thrown correctly
      done();
    });
  });
});
Comments