Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jasmine: Expecting Error to be Thrown in a Async Function

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...

like image 926
hosjay Avatar asked Jul 03 '17 00:07

hosjay


People also ask

Does Jasmine support asynchronous operation?

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.

How do you throw a Jasmine error?

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(); }); });

Does Jasmine support asynchronous operations Mcq?

Q: Does Jasmine support asynchronous operations? Ans: It's possible that the functions you supply to beforeAll, afterAll, beforeEach, and afterEach are asynchronous.

What is asynchronous testing?

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.


1 Answers

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'));
});
like image 121
Matti Lehtinen Avatar answered Oct 10 '22 23:10

Matti Lehtinen