Search code examples
angularangular-unit-test

Error:- Can't read property variable of undefined during unit testing


variable from service is coming as undefined

Below is my ts file

ngOnInit() {

        this.serviceElectionForm.form = this.formBuilder.group({});

     /****
         * commenting below, if condition,  doesnt cause any error in spec file
         */
        if (this.registerService.submitReg.isAdminFlow) {
          this.companyDesignationForm.form = this.formBuilder.group({});
        }


        this.userAuthenticationForm.form = this.formBuilder.group({});
        this.roleDesignationForm.form = this.formBuilder.group({});

      }

below is my spec file

fdescribe('RegisterComponent', () => {
  let component: RegisterComponent;
  let fixture: ComponentFixture<RegisterComponent>;



  const MockRegisterService = {
    isAdminFlow: true,
  }

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        RegisterComponent,

      ],
      imports: [
        AngularMaterialsGlobalModule,
        RouterTestingModule,
        ReactiveFormsModule,
        NoopAnimationsModule,
        HttpClientTestingModule
      ],
      providers: [
        { provide: RegisterService, useValue: MockRegisterService },
        CookieService
      ]
    }).compileComponents();
  }));

  describe('Base instantiation and component creation', () => {

    beforeEach(() => {
      fixture = TestBed.createComponent(RegisterComponent);
      component = fixture.componentInstance;
      fixture.detectChanges();
    });

    it('should create register component ', () => {
      expect(component).toBeTruthy();
    });
  });

The error which I am getting is

typeError: Cannot read property 'isAdminFlow' of undefined TypeError: Cannot read property 'isAdminFlow' of undefined at RegisterComponent../src/app/pages/registration/register.component.ts.RegisterComponent.ngOnInit


Solution

  • Try this, your service is expecting to have a property called submitReg inside that property resides isAdminFlow

    const MockRegisterService = {
        submitReg:{
         isAdminFlow: true,
        }
      }