#how to mock a token?
5 messages · Page 1 of 1 (latest)
Just test the logic in the response handling
Sweet. So that means we need to use HttpClientTestingModule which you've already imported 👍 .
Also since this is a unit test, we want to isolate your ApplicationService by mocking all other dependencies. So we need to mock AuthenticationService as well. We can do this by replacing AuthenticationService in your test's providers array with a spy.
Like so:
providers: [ApplicationService, {provide: AuthenticationService, useValue: jasmine.createSpyObj('AuthenticationService', ['someMethod', 'anotherMethod'])],
There is multiple ways to mock services, but that's the way I prefer. You might find a better way in the future.
Now when you inject the AuthenticationService, you need to change its type to SpyObj<AuthenticationService>.
So authenticationService = TestBed.inject(AuthenticationService) as SpyObj<AuthenticationService>, because we changed the value of the AuthenticationService in the providers array to a jasmine spy object.
Also need to add a new variable at the top: let authenticationService: SpyObj<AuthenticationService>.
Now you have the ability to mock any methods from the AuthenticationService that is used inside the ApplicationService.
For example, if you have a method from the AuthenticationService called getToken(): string, then you can stub the return by doing this:
authenticationService.getToken.and.returnValue('myToken');
@stoic geyser you need to create a new variable at the top to assign this to.
let authenticationService: SpyObj<AuthenticationService>;
g!rule3