admin管理员组文章数量:1291383
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".
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".
- Do you have babel (specifically babel-polyfill) in your build-stack? You should be able to use async/await to wait for the promise to be fulfilled. – Nik Commented Aug 26, 2016 at 12:19
-
Notice that Jasmine allows synchronous specs with
jasmine.clock
(an alternative to A1's$rootScope.$digest()
). – Estus Flask Commented Aug 26, 2016 at 12:37
2 Answers
Reset to default 7The 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'))
});
本文标签: javascriptHow to test a method returning a PromiseStack Overflow
版权声明:本文标题:javascript - How to test a method returning a Promise - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741528385a2383606.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论