1

i am trying to setup unit tests using inject. But i am not sure how to set the parameters.

The constructor for the class being tested (auth.service.ts) is:

constructor(private http : HttpClient, private token: TokenStorage) {}

Unit Test class (auth.service.spec.ts)

import { TestBed, inject } from '@angular/core/testing';
import { AuthService } from './auth.service';
import { HttpClient, HttpHandler, HttpClientModule } from '@angular/common/http';
import { TokenStorage } from './token.storage';

describe('AuthService', () => {
    beforeEach(() => {
        TestBed.configureTestingModule({
            providers: [AuthService, HttpClient, HttpHandler, HttpClientModule, TokenStorage]
        });
    });
    it('should be created', inject([AuthService], (service: AuthService) => {
        expect(service).toBeTruthy();
    }));
});
3

1 Answer 1

2
  1. You need to use the HttpClientTestingModule to test HttpClient usage in your service.
  2. Use a fake value for TokenStorage, otherwise your unit test becomes an integration test.

See also angular - Testing services with the TestBed

import { TestBed, inject, getTestBed } from '@angular/core/testing';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { AuthService } from './auth.service';
import { TokenStorage } from './token.storage';

describe('AuthService', () => {
  let injector: TestBed;
  let service: AuthService;
  let httpMock: HttpTestingController;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule],
      providers: [
        AuthService,
        { provide: TokenStorage, useValue: {} }
      ]
    });
    injector = getTestBed();
    service = injector.get(AuthService);
    httpMock = injector.get(HttpTestingController);
  });

  afterEach(() => {
    httpMock.verify();
  });

  it('should be created', () => {
    expect(service).toBeTruthy();
  });
});
Sign up to request clarification or add additional context in comments.

1 Comment

I get the following error: Error: StaticInjectorError(DynamicTestModule)[AuthService -> HttpClient]: error properties: Object({ ngTempTokenPath: null, ngTokenPath: [ 'AuthService', Function ] })

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.