【问题标题】:Provider not found when injecting in Angular unit tests?注入Angular单元测试时找不到提供程序?
【发布时间】:2019-05-15 21:30:21
【问题描述】:

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

}

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

【问题讨论】:

  • 尝试在单元测试中删除providers 数组中服务名称周围的单引号。

标签: angular unit-testing mocking components


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多