首页 > 解决方案 > 测试 Angular 库时依赖注入失败

问题描述

我创建了一个 Angular 库,其中包含一个简单的组件和一个服务,该服务执行 HTTP 调用并获取结果,然后在组件中使用该结果。

除了测试不会通过依赖注入错误之外,所有工作都找到了:

Error: StaticInjectorError(DynamicTestModule)[HttpClient]:
   StaticInjectorError(Platform: core)[HttpClient]:
   NullInjectorError: No provider for HttpClient!

以下是我的代码供参考:

@Injectable({
  providedIn: "root"
})
export class MyService {
  public apiUrl = "https://apiurl";

  constructor(private http: HttpClient) {}

  getSomeData(key: string): Observable<string> {
    return this.http.get(
      `${this.apiUrl}/${key}`,
      { responseType: "text" }
    );
  }
}

和测试:

describe('MyService', () => {
  let injector : TestBed;

  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [
        MyService
      ],
      imports: [
        HttpClientTestingModule
      ],
    });

    injector = getTestBed();

  });

  it('should be created', () => {
    const service = injector.get(MyService);
    expect(service).toBeTruthy();
  });
});

我的猜测是这与@angular-devkit 有关,但我可能错了。是的,我已经尝试了所有变体,甚至尝试注入真正的 http-client 也不起作用。

标签: angulardependency-injection

解决方案


我查看了您的存储库,发现您专注于ngx-pass-strength.service.spec.ts文件,但忘记了您没有HttpClientTestingModule在测试中导入组件。

ngx-pass-strength.component.spec.ts

TestBed.configureTestingModule({
  declarations: [ NgxPassStrengthComponent ],
  imports: [
    HttpClientTestingModule  <== add this
  ],
})
.compileComponents();

推荐阅读