注入Angular单元测试时找不到提供程序?

时间:2018-12-14 15:30:04

标签: angular unit-testing mocking components

我有一个在其构造函数中接收类的服务。我嘲笑了注入的服务,并将其作为提供程序添加到了测试模块中,并在测试组件中进行了覆盖,但是我仍然得到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;
  }

}

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

1 个答案:

答案 0 :(得分:1)

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

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