0

I would like to ask how is it with Dependency Injection in Angular4 and how it can be used for mocking services in Unit Tests.

First at all, I didn't check on any Angular2 testing framework, at this point, I'd like to know more about the general concept.

Why is DI in Angular being called DI at all?

When you list a service in a constructor to be injected, you have to import the reference to the file.

When you register a service in the providers, it's just a class name. I don't see here any possibility of Interface - Class pairing.

I cannot resist, but I see no difference from this behavior to static classes.

What would be the technic to somehow mock the service for unit tests?

Many thanks for all inputs :)

Václav Mikeska
  • 497
  • 4
  • 9
  • Have you checked https://docs.angularjs.org/guide/di and https://angular.io/guide/testing chapters before asking? SO is helpful community but the questions that lack any reseach aren't appreciated in general. Regarding DI, the thing that is being injected in constructor with `ClassName` token is not a class itself, it can be class instance, or another class, or another class instance. – Estus Flask Sep 22 '17 at 11:17
  • Yes, I have made some research, Google didn't offer me anything interesting... The link provided is for the previous version of the Angular. – Václav Mikeska Sep 22 '17 at 12:05
  • Oh, sorry, missed the second one. But I'm not interested just only of the unit testing, but of DI generally. On that topic I really didn't find anything, just basic description of the functionality. That thing with the supplying reference could be the first interesting thing, will have a look on it. – Václav Mikeska Sep 22 '17 at 12:10
  • The first link was wrong. The main idea behind Angular DI is that there can be different provider types that define the value that will be injected https://angular.io/guide/dependency-injection#injector-providers . DI token can be a string that doesn't need an import, but this practice is heavily discouraged. – Estus Flask Sep 22 '17 at 12:18
  • Possible duplicate of https://stackoverflow.com/questions/36109555/how-to-use-dependency-injection-di-correctly-in-angular2 – Estus Flask Sep 22 '17 at 12:20

1 Answers1

0

What would be the technic to somehow mock the service for unit tests?

You can inject a service into your test after declaring it in the testbed. An example:

it('should mock videos', inject([VideoService], (videoService: VideoService) => { 
    videos = [
        { id: 0,  name: 'Superman' },
        { id: 1, name: 'Superman part 2' }
      ]
    spyOn(videoService, 'videos').and.returnValue(videos); 
    fixture.detectChanges();
    expect(component.getVideoOne()).toContain(Superman);

  });
Swoox
  • 3,707
  • 2
  • 21
  • 32