0

I have this task of implementing tests for some components implemented by someone else. I try to not make changes on their code, but I find it hard because they made all the methods private, also they make an HTTP request and subscribe to it inside the method which give me a trouble figuring out what the best test scenario will be. Here is an example:

private getProfile() {
    this.http
      .get('go/profile/get', {withCredentials: true})
      .subscribe((profile: Profile) => {
        this.user.profile = profile;
        this.updateLineMsgs();
      });
  }

So to sum up:

  1. Can I test a private method or am I obliged to change its scope?

  2. What is the best test scenario for such case?

4
  • 1. no, but you can test the component using that private method. 2. To test the component as a black box, by mocking the http backend as explained in the HttpClient guide: angular.io/guide/http#testing-http-requests Commented Nov 17, 2019 at 9:43
  • Test the side effect - presumably the update method does something? You can also test that the user property is updated. Commented Nov 17, 2019 at 9:53
  • @JBNizet 1- yeah but I don't see how I can test the private method, I used the test bed and all but I still can't access it from the spec file. Commented Nov 17, 2019 at 10:02
  • 1
    You shouldn't need to access it, just simulate the conditions that invoke it (e.g. clicking a button). Commented Nov 17, 2019 at 10:05

1 Answer 1

2

You can see this answer, and this answer how to test private methods.

In my view, you should not test private methods as private methods are implementation details, these methods are encapsulated in your class/API. Private methods is a tool which helps to create desired behavior for public methods(API). Some reasons to avoid writing unit tests for private methods:

  • implementation of private methods can be changed in future. So your current tests for private methods are fragile and if they should be considered to be rewritten
  • Unit testing is for testing the public interface of your code, so when the private implementation changes, you can run your tests and be sure it still works the same for the outside world.
  • Follow "the duck test": "If it looks like a duck, swims like a duck, and quacks like a duck, then it probably is a duck.". You test just the output.

So you need to test public methods and if these public methods are okay, then we can think that private methods are okay. So you should instead test the end result of your public functions.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.