Angular 7 Component Test is using original service instead of mock
I see two issues in the code above:
- You have an extra set of square brackets in the providers array of your TestBed. I don't think this is a major issue, it is just semantically incorrect.
- When you provide
HelloWorldService
in the providers array, you have specifieduseClass
, but have provided an object (which is whatjasmine.createSpyObj()
produces), so you should instead specifyuseValue
.
I hope this helps.
Update:
Ok, you have come quite a long ways! You corrected the two problems I outlined above, have done the overrideProvider()
before the compileComponents()
as I suggested in a comment to another answer as well as wrapped the beforeEach()
inside an async()
.
The reason I asked to see all the other code was so I could quickly put it up in the following StackBlitz for testing. As you can see in that StackBlitz, the test is now passing.
I only added one line in the beforeEach()
to declare a returnValue from your spy, so that the subscribe in your component has an Observable to subscribe to:
mockHelloWorldService.getHelloWorld.and.returnValue(of('Test Message'));
I added this before the call to fixture.detectChanges()
since this will invoke ngOnInit()
, and the spy needs a return value set BEFORE executing ngOnInit()
so that it will execute correctly and not give you the error you were seeing.
I also added a line in the spec to show how you can test that the result of the Observable is correctly set to your component variable:
expect(component.helloWorldMessage).toEqual('Test Message');
Note that you are significantly complicating your testing by specifying the HelloWorldService in the providers array of your component declaration. If you instead provide this service as a singleton in root that will simplify things a lot, including how you test. See details in the Official Docs.
Maybe your HelloWorldService is declared in the component providers. So you need to use https://angular.io/api/core/testing/TestBed#overrideComponent to replace the provider.