代码之家  ›  专栏  ›  技术社区  ›  b. e. hollenbeck

在角度单元测试中注入时未找到提供程序?

  •  0
  • b. e. hollenbeck  · 技术社区  · 7 年前

    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 回复  |  直到 7 年前
        1
  •  1
  •   R. Richards    7 年前

    删除中服务名称周围的单引号 providers 单元测试中的数组应该可以做到这一点。

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