Avinash Raj
Avinash Raj

Reputation: 174706

`ng test` shows Error: Can't resolve all parameters for BackendService

Below error shown when I ran ng test command.

Here is my service spec,

describe('BackendService', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [
        {
          provide: Http, useFactory: (backend, options) => {
            return new Http(backend, options);
          },
          deps: [MockBackend, BaseRequestOptions]
        },
        MockBackend,
        BaseRequestOptions,
        BackendService
      ]
    });
  });

  it('should ...', inject([BackendService, MockBackend], (service: BackendService) => {
    expect(service).toBeTruthy();
  })

); });

BackendService.ts looks like,

export class BackendService {
  private baseUrl: string = 'https://foo-backend.appspot.com/_ah/api/default/v1';

  constructor(private http: Http, baseName: string) {
    this.baseUrl = this.baseUrl + baseName;
  }
  .....
}

It seems like extra parameter inside the BackendService class's constructor causes this problem..

Upvotes: 0

Views: 156

Answers (1)

Paul Samsotha
Paul Samsotha

Reputation: 208994

How do you expect Angular to know what baseName is supposed to be? All constructor parameters need to be obtained from the Injector. And if there is no corresponding token for the parameter, then it can't be looked up.

You can add a token by doing

// somewhere in some file
import { OpaqueToken } from '@angular/core';

export const BASE_NAME_TOKEN = new OpaqueToken("app.base_name");

// in test class
import { BASE_NAME_TOKEN } from 'where-ever'

TestBed.configureTestingModule({
  providers: [
    BackendService,
    { provide: BASE_NAME_TOKEN, useValue: 'whatever-the-base-is' }
  ]
});

// in service constructor
import { Inject } from '@angular/core'
import { BASE_NAME_TOKEN } from 'where-ever'

constructor(http: Http, @Inject(BASE_NAME_TOKEN) baseName: string) {}

See Also:

Upvotes: 1

Related Questions