简体   繁体   中英

How to test a method returning a Promise

I'm writing an Angular 2 RC5 application, and unit testing using Karma and Jasmine.

I have a method that returns a Promise<Foo> (It's on top of a call to angular's http.post) I want to run some assertions after that finishes.

Something like this doesn't work

let result = myService.getFoo();
result.then(rslt => expect(1+1).toBe(3)); // the error is lost

This creates an 'Unhandled Promise rejection' warning, but the error is suppressed and the test passes. How do I run assertions based on my resolved promise?

Notes:

  • The .catch() method doesn't seem to be what I'm after. I don't want to log or do anything that continues normal program flow, I want to fail the test.
  • I've seen code that looks like $rootScope.$digest(); . I'm not sure what the typescript equivalent of this sort of thing is. There doesn't seem to be a way of saying: "I have a promise, I'm going to wait here until I have a synchronous result".

The test should look something like this:

it('should getFoo', function (done) {
  let result = myService.getFoo();
  result
    .then(rslt => expect(rslt).toBe('foo'))
    .then(done);
});

Using the done callback works, but you should be able to do this as well:

(Note the return )

it('should getFoo', function () {
  let result = myService.getFoo();
  return result
    .then(rslt => expect(rslt).toBe('foo'))
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM