I have an async function in my angular2 app for which I want to write a unit test. Imagine my function is like this:
myFunc(a: int): Promise<void> {
if (a == 1)
throw new Error('a should not be 1');
let body = {
value: a
};
return apiService.patch('/url/', JSON.stringify(body)).toPromise();
}
Now, I'm thinking of checking that if condition. I tried the following code; but, this test always fails since my code actually does not wait for any results:
it('should throw error if a = 1', () => {
expect(() => {
mySerivce.myFunc(1);
}).toThrow(new Error('a should not be 1'));
})
I don't know how I should write unit tests for these types of logics...
Jasmine supports three ways of managing asynchronous work: async / await , promises, and callbacks. If Jasmine doesn't detect one of these, it will assume that the work is synchronous and move on to the next thing in the queue as soon as the function returns.
Let us modify our JavaScript with the following set of code. var throwMeAnError = function() { throw new Error(); }; describe("Different Methods of Expect Block", function() { var exp = 25; it ("Hey this will throw an Error ", function() { expect(throwMeAnError). toThrow(); }); });
Q: Does Jasmine support asynchronous operations? Ans: It's possible that the functions you supply to beforeAll, afterAll, beforeEach, and afterEach are asynchronous.
Asynchronous code doesn't execute directly within the current flow of code. This might be because the code runs on a different thread or dispatch queue, in a delegate method, or in a callback, or because it's a Swift function marked with async . XCTest provides two approaches for testing asynchronous code.
Nowadays jasmine (3.3+) supports this natively:
https://jasmine.github.io/api/3.4/async-matchers.html
it('should...', async () => {
await expectAsync(myService.myFunc(1))
.toBeRejectedWith(new Error('a should not be 1'));
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With