Check out a free preview of the full Angular Core course:
The "Services" Lesson is part of the full, Angular Core course featured in this preview video. Here's what you'd learn in this lesson:

Lukas demonstrates how to use a mock in a component that uses a service.

Get Unlimited Access Now

Transcript from the "Services" Lesson

[00:00:00]
>> Lukas Ruebbelke: Now one of the thing that I will call out that is interesting is that if you have a component that has a service, typically what you're going to want to do is, like for an instance let's take project service and It's not necessarily a problem. In other words, it's able to run just fine.

[00:00:31] But if I wanted to mock out projectService, and so I'm gonna show this. And I'm not gonna complete this example, but I do wanna show how this works. Is, what I would do is, I would go projectService and so again creating like another reference to the local member, and this is going to be of type projectService, it's like you're not instantiating it.

[00:01:05] But what I'll also do is, I'll create a mock service. So I might call this, whatever. And this can be a couple things, it can be a class, it can be an object, whatever. And so mark yourself out. And then, with in your module fixture here, or your module class, you can go providers.

[00:01:40] Let's see if I can do this from memory. It's an object and it's provide, I think this is it, and I can double check in just a moment. But we're going to provide projectService, but what we really want to do is, use value of mock projectService here. And so what we're doing is we're overriding, for saying, I want to inject the projectService.

[00:02:31] But I'm going to use value, the mock projectService. It's using essentially this object, you're saying provide this but instead use value this. You can also do it as a class, so for instances, if I needed a little bit more extensive of a mock, then I'll do that as well.

[00:02:48] And then when you want to get an instance of that service on the component, you can go here and, I'll just put it up here. So get service instance. And I think I'd call this, see here, projectsService=debug injector.get, projectService. So now this allows us to, not that I would test the service directly, but I would want to spy on it.

[00:03:36] Or if I had a heart dependency on something with in the component, then I would just overwrite that and say, you're calling this method but instead of returning me real stuff, I want you to just provide this mock data, or whatever. And so this is how you get a service onto a component.

[00:03:56] From there you can mark it out and then spy on it.