Вопрос

After reading so many posts on AngularJS testing with Jasmine, I came to the conclusion that the way I built my service is not a testable one.

But still, I'm too much of a noob on AngularJS to really grasp a better way of doing it. Some of my colleagues tell me that I can test nested methods, but it doesn't seem so.

So, here's the situation:

I have a service that performs a GET to a restfull webservice and returns an object.

it looks like so:

.factory('MyService', function( $resource, config, $q ) {
    return config.get("RestServiceBaseUrl").then(function(baseUrl) {
        return $resource(baseUrl+"params_necessary_to_my_rest_call")
    })
 })

It has that config injected, which is a service as well, that will return me whatever I have in a physical config file, in this case, it's a url, that is stored under a RestServiceBaseUrl JSon variable. Anyhow, here's the get part of my injected config object:

function get(sKey) {
    var deferred = $q.defer()

    ConfigGet(sKey, function (resp) {
        deferred.resolve(resp['result'])
    })

    return deferred.promise
}

So, as you can see, I have to nested returns, one for the config.get method, whence comes from a service; and the other one is the return from the GET, which is also dependent on the $resource, injected as well on my service. That $resource comes from the angular-resources. Nothing has been done to override it.

In my unit tests, I have tried so many ways of achieving a test, but it's frustrating, because when I get passed the config problem, I get the $resource problem, and I can't seem to do it right when it comes down to testing services with injected services.

Here's my code at Plunker: http://plnkr.co/edit/RSFTKq

As you can see, I'm attempting to test the returning value form my service.

I'm on this thing for 4 days already! I'm in despair! Any help will be greatly appreciated!

Please, excuse my English mistakes.

Regards

Это было полезно?

Решение

I think there might be a bug that is preventing you from doing exactly what you want to do - end-to-end testing. If you are allowing your HTTP requests to go all the way to a third-party URL (i.e. you're not mocking their replies) you are not doing unit tests.

Here's a working example of an end-to-end test, save the call to twitter itself (because of the issue I mentioned). Basically here were the issues with your test code:

  • You were getting returned a promise that you weren't then-ing.
  • You need to call get or something on the returned angular resource from the promise to make a call on the resource.
  • You were comparing a string to an object (I JSON.stringify()-ed the object for you).
  • You need to mock out the HTTP request (or get passThrough() working - which I couldn't).

And here's the result:

http://plnkr.co/edit/8WIPmm?p=preview

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top