Testing errors and promises with jasmine

Jacopo Lanzoni

Testing errors and promises. I have a situation similar to the one below:

public myUtilityMethod(): Promise<string> {
  // some synchronous stuff
  console.log('bla bla');
  // some asynchronous stuff
  return Promise.resolve('ok');
}
public async doSomething(): Promise<void> {
  let promise;
  try {
    promise = this.myUtilityMethod();
  } catch (e) {
    throw new MyError('I knew it', e, {});
  }
  await Promise.all([promise]);
  return Promise.resolve();
}

I want to test, when something goes wrong in the synchronous part of myUtilityMethod, I throw a MyError, so I write the following test

it('should throw MyError when something goes wrong in the synchronous part of myUtilityMethod', fakeAsync(() => {
  // given
  const error = new Error('something went wrong');
  component.myUtilityMethod = sinon.stub().throws(error);
  // when
 expect(() => {
   component.doSomething();
   flushMicrotasks();
 }).toThrow(jasmine.any(MyError));
}));

The test fails because

        Error: Expected function to throw <jasmine.any(MyError)>, but it threw Error: Uncaught (in promise): MyError: {"message":"i knew it","nativeError":{},"context":{}}.

Am I missing something obvious?

Jacopo Lanzoni

async functions wrap all their content in a promise, so even if the error is thrown before any "await" is encountered, what happens is that the promise rejects instead of throwing an error. The following test passes:

  it('test test', (done) => {
    const error = new Error('something went wrong');
    component.myUtilityMethod = sinon.stub().throws(error);

    component.doSomething().catch((e) => {
      expect(e).toEqual(jasmine.any(MyError));
      done();
    });
  });

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related