Reputation: 1750
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?
Upvotes: 0
Views: 117
Reputation: 366
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();
});
});
});
Upvotes: 1
Reputation: 55962
Jasmine is a unittest framework, it provides a test runner, assertion methods and mocks/spies based in. It is a popular way to unittest javascript code. It is no better than any of the other ways / frameworks available and should be evaluated against the other options to see if it is a correct fit for your project.
Without example code, unittesting promises should be no different than unittesting any other code. Stub the IO dependencies and evaluate all critical logic paths. If your promise explicitly throws than catch
could be a valuable method to assert on. Same with then
, calling then
should allow you to test your resolve logic.
Having to interact with your code through then
and catch
may not be the most effective way to exercise your promise logic. If there is significant amount of logic it is good to encapsulate that in a function outside of promise, to allow for easier unittesting. Then the interface to that core logic could lightly be tested through resolving the promise.
Upvotes: 0