错误:无法在单元测试期间读取未定义的属性变量

时间:2019-06-18 16:45:58

标签: angular angular-unit-test

服务变量未定义

下面是我的ts文件

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

      }

下面是我的规格文件

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

我得到的错误是

typeError:无法读取未定义的属性'isAdminFlow' TypeError:无法读取未定义的属性“ isAdminFlow”     在RegisterComponent ../ src / app / pages / registration / register.component.ts.RegisterComponent。ngOnInit

1 个答案:

答案 0 :(得分:0)

尝试一下,您的服务期望在其中包含名为submitReg的属性isAdminFlow

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