0

I my angular project I have a service1 that depends on service 2. Service1 is sending a rather complex function for callbackSuccess into service2

service2.js

 this.getData = function (url, callbackSuccess, callbackError) {

I'm not sure whether there is much point unit testing service2 and I should rather focus on service1 since most of the logic is contained in there. Can someone advise?

2 Answers 2

2

You could simply create a spy on the function in service2 or mock out service2 completely.

var data_spy = spyOn(service2, 'getData').andCallFake(
    function(url, callbackSuccess, callbackError) {
        callbackSuccess(mock_data); // Mock the data somewhere
    }
);

Using this is a good idea since it removes the dependence on service2 functionality in your test. Although you should still consider testing service2.

Some other advice. This model seems to lend itself very well to promises, since there is a resolve and reject callback. I recommend you take a look at $q documentation.

Hope this helped!

Sign up to request clarification or add additional context in comments.

Comments

1

Should you test service2?

If service2 is obviously correct because it is so simple you can inspect it - then you probably do not need tests for it. However if it is any more complex then that, then you probably want to test it.

I can see that it must be doing at least 3 things:

  1. does something with url
  2. calls success callback only if operation was successful, and calls it with all the correct parameters based upon output of operation
  3. calls error callback only if operation was not successful, and calls it with all the correct parameters based upon the output (such as error codes and messages)

To me, this amount of work would lead me to add some tests - haven't even though about exception handling for instance... The testing of it, since it is simple, should also be simple.

Testing service1

If service1 contains a complicated callback then it definitely should be tested. Make sure that callback is accessible from your tests so you can test it thoroughly in isolation from the rest of what service1 might be doing before passing it off to service2.

Conclusion

Ultimately you are asking an opinion question, and one that relies upon a lot of information about your codebase, goals, and deadlines which we do not know. My best answer is: test service2.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.