简体   繁体   中英

Test a service with a promise inside in Angular with Karma-Jasmine

I am starting to test a service in Angularjs with Karma and Jasmine. I have no idea how $q works, i have never use it and anyway i do not know if it is necessary here. My problem is that I have a service which have 1 function which calls another function inside the service (with a promise):

This is the function which calls sendMetrics (which has the promise)

在此处输入图片说明

This is my test, i have tried with $q using $digest, but i get an error about cookies (I have search it and it could be because of my angular - jasmine versions). Also I have tried with jasmine spy, but i do not want to build again all the service.

I just want to resolve the promise to check that test value is 2 and not 1. 在此处输入图片说明

This is the function which has the promise. 在此处输入图片说明

Maybe this question is duplicated or not, but i need an answer for people who do not know how to use $q, if I need to use it. Until now, I have not found anything helpful.

I think that you have to return the promise directly in sendMetrics and then handle it in sendSearchMetrics. Right now, you are not returning a promise from within the promise in sendMetrics but you are trying to use it as if it were a Promise.

Finally I got it:

Just add the httpBackend in a beforeEach and then use $httpBackend.expect(...)

After that call your promise function and use the $httpBackend.flush() and you will get it working.

在此处输入图片说明 在此处输入图片说明

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