Angular Компонентный тест TypeError: Невозможно прочитать свойство 'subscribe' из неопределенного - PullRequest
0 голосов
/ 06 апреля 2020

Я получаю это сообщение об ошибке при запуске теста ng:

Chrome 80.0.3987 (Windows 10.0.0) ProfileComponent should be created FAILED
TypeError: Cannot read property 'subscribe' of undefined
        error properties: Object({ ngDebugContext: DebugContext_({ view: Object({ def: Object({ factory: Function, nodeFlags: 33800193, rootNodeFlags: 33554433, nodeMatchedQueries: 0, flags: 0, nodes: [ Object({
 nodeIndex: 0, parent: null, renderParent: null, bindingIndex: 0, outputIndex: 0, checkIndex: 0, flags: 33554433, childFlags: 245760, directChildFlags: 245760, childMatchedQueries: 0, matchedQueries: Object({  }
), matchedQueryIds: 0, references: Object({  }), ngContentIndex: null, childCount: 1, bindings: [  ], bindingFlags: 0, outputs: [  ], element: Object({ ns: '', name: 'app-profile', attrs: [  ], template: null, c
omponentProvider: Object({ nodeIndex: 1, parent: <circular reference: Object>, renderParent: <circular reference: Object>, bindingIndex: 0, outputIndex: 0, checkIndex: 1, flags: 245760, childFlags: 0, directChil
dFlags: 0, childMatchedQueries: 0, matchedQueries: Object, matchedQueryIds: 0, references: Object, ngContentIndex: -1, childCount: 0, bindings: Array, bindingFlags: 0, outputs: Array ...
            at <Jasmine>
            at new CertificationService (http://localhost:9876/_karma_webpack_/src/app/components/cts/services/certification.service.ts:66:3)
            at _createClass (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/fesm2015/core.js:30472:1)
            at _createProviderInstance (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/fesm2015/core.js:30426:1)
           ...

мой тест:

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

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [ReactiveFormsModule, FormsModule,HttpClientModule ],
      declarations: [ ProfileComponent,CertificationsComponent ,NumericOnlyDirective ],
      providers: [
        PrService,
        UsService,
        InService,
        CertificationService,
        HttpClient,
        CookieService
      ]
    })
    .compileComponents();
  }));

  it('should be created', done=>inject([UsService,HttpClient,CookieService,PrService,CertificationService],
    async (usService: UsService,http: HttpClient, cookieService: CookieService,prService: PrService,certificationService:CertificationService,inService: InService) => {
      const response = {};
      const a: BehaviorSubject<any> = new BehaviorSubject(response);
      spyOn(usService, 'getObsU').and.returnValue(a.asObservable());
      spyOn(cookieService, 'get').and.returnValue('aasdf');
      spyOn(prService, 'getResponseObs').and.returnValue(a.asObservable());
      spyOn(prService, 'getPrObs').and.returnValue(a.asObservable());
      spyOn(inService, 'getIn').and.returnValue(a.asObservable());

      fixture = TestBed.createComponent(ProfileComponent);
      component = fixture.componentInstance;
      fixture.detectChanges();
      expect(component).toBeTruthy();
      done();
  })());
});

вот мой инициализатор и конструктор компонента компонента:

  constructor(
    private prService: PrService,
    private inService: InService,
    private certificationService: CertificationService,
    private usService: UsService
  ) {
    this.prService.getPrObs().subscribe(p=> {
        this.p= p;
      }
    });
    this.prService.getResponseObs().subscribe(apiResponse => {
      this.serviceResponse = apiResponse
    });
    this.inService.getIn().subscribe(reasons => {
      this.reasons = reasons
    });
    this.usService.getObsU().subscribe( u => {
      this.u = u;
    });
  }

  ngOnInit() {
    this.formErrors = [];
    this.showCertifications = false;
    if (!this.currentProfile) {
      this.formSsn = '';
      this.resetForm();
    } else {
      this.setProfile(this.currentProfile);
    }
  }

Я пытался использовать фиктивные сервисы, но это выдает мне ту же ошибку / другие ошибки, говоря, что методы не существуют. Этот компонент также имеет подкомпонент, CertificationsComponent. Я делаю этот тест, чтобы просто добиться успешного создания компонента по умолчанию. он показывает ошибку 4 раза, дважды для компонента профиля и дважды для компонента сертификации. все они говорят в новом CertificationService.

1 Ответ

0 голосов
/ 14 апреля 2020

, поэтому я использовал ngentest, чтобы просто автоматически создать работающий тест, и это сработало. вот оно:

все фиктивные сервисы находятся наверху и выглядят так:

@Injectable()
class MockUsService {
  getObsU= function() {
    return observableOf({});
  };
}

и остальные:

describe('ProfileComponent', () => {
  let fixture;
  let component;
  const matDialogRefStub = {};

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [ FormsModule, ReactiveFormsModule,OverlayModule,MatDialogModule  ],
      declarations: [
        ProfileComponent,
      ],
      schemas: [ CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA ],
      providers: [
        { provide: PrService, useClass: MockPrService },
        { provide: InService, useClass: MockInService },
        { provide: CertificationService, useClass: MockCertificationService },
        { provide: UsService, useClass: MockUsService },
        {provide: MatDialogRef, useValue: matDialogRefStub},
        MatDialog
      ]
    }).overrideComponent(ProfileComponent, {

    }).compileComponents();
    fixture = TestBed.createComponent(ProfileComponent);
    component = fixture.debugElement.componentInstance;
  });

  afterEach(() => {
    component.ngOnDestroy = function() {};
    fixture.destroy();
  });

  it('should run #constructor()', async () => {
    expect(component).toBeTruthy();
  });
  it('should run #ngOnInit()', async () => {
    component.ngOnInit();
  });
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...