首页 > 解决方案 > 注入 Angular 单元测试时找不到提供程序?

问题描述

我有一个在其构造函数中接收一个类的服务。我已经模拟了注入的服务并将其添加为测试模块中的提供程序并在测试组件中被覆盖,但我仍然得到NullInjectorError: No provider for UserService!

这是测试 - 请放心,我已经导入了我需要的所有内容:

describe('DataConsentComponent', () => {
  let component: DataConsentComponent;
  let fixture: ComponentFixture<DataConsentComponent>;

  class UserMock extends User {

    constructor () {
      super();
    }
  }

  class UserServiceMock {

    constructor () {

    }
  }

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [DataConsentComponent],
      providers: [
        { provide: 'UserService', useClass: UserServiceMock },
        { provide: 'User', useClass: UserMock }
      ]
    });

    TestBed.overrideComponent(
      DataConsentComponent,
      {
        set: {
          providers: [
            { provide: 'UserService', useClass: UserServiceMock },
            { provide: 'User', useClass: UserMock }
          ]
        }
      });

    fixture = TestBed.createComponent(DataConsentComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();

  }));


  it('should create', inject([UserService], () => {
    expect(component).toBeTruthy();
  }));
});

和被测试的类:

import { Component, OnInit } from '@angular/core';
import { UserService } from '@team/user.service';
import { User } from '@team/user.model';
import { GDPR_IS_ACTIVE } from '../../config/constants';

@Component({
  selector: 'app-data-consent',
  template: ''
})

export class DataConsentComponent {

  public User: User;

  constructor(private UserService: UserService){
    this.UserService.UserSource$.subscribe(
      (User: ETMUser) => {
        this.User = User;
    });
  }

  getGDPRIsActive(): boolean {
    return GDPR_IS_ACTIVE() || false;
  }

  getIfUserIsClient() {
    return this.UserService.getUserIsClient();
  }

  getIfUserIsEmployee() {
    return this.UserService.getUserIsEmployee();
  }

  showCandidateGDPRInformation (candidate) {
    return true;
  }

  getNavigateLinkLabel(candidate):any {
    return 'View';
  }

  shouldShowNavigate(candidate) {
    return true;
  }

  isSelectable(candidate) {
    return true;
  }

}

如果有更好的方法来获得该服务,我非常愿意重构。

标签: angularunit-testingmockingcomponents

解决方案


providers在单元测试中删除数组中服务名称周围的单引号应该可以解决问题。

您希望 TestBed 将它们作为类/对象提供,而不是字符串或标记。


推荐阅读