0
votes

I get this error message when running ng test :

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)
           ...

my test:

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();
  })());
});

here is my init and constructor of the component component:

  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);
    }
  }

Ive tried using a mock services, but it would give me the same error/ other errors saying methods do not exist. This component also has a subcomponent, CertificationsComponent. I am making this test to just get the default component creation to be successful. it shows the error 4 times, twice for the profilecomponent and twice for the certification component. all of them say at new CertificationService.

1
Is certification Service in same module? If not, then you need to import that module And where you are subscribing the CertificationService's method?Shoaib Chikate
@ShoaibChikate everything is in the same module. I am not subscribing to any certificationservice method within my profile componentJordendarc

1 Answers

0
votes

so I used ngentest to just automatically generate a working test and it worked. here it is:

all mock services are at the top and look like this:

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

and the rest:

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();
  });