简体   繁体   English

ng test显示错误:无法解析BackendService的所有参数

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

Below error shown when I ran ng test command. 我执行ng test命令时显示以下错误。

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, BackendService.ts看起来像

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.. 似乎BackendService类的构造函数中的额外参数导致了此问题。

How do you expect Angular to know what baseName is supposed to be? 您如何期望Angular知道baseName应该是什么? All constructor parameters need to be obtained from the Injector. 所有构造函数参数都需要从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: 也可以看看:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM