2

I am facing an error while doing Angular unit testing. I am trying to test create component Please see error below file and let me know why I am facing that, I also import the services related with the providers and imports for the module.

the below error is shown by Karma while unit testing. I think I am missing something

TypeError: Cannot read property 'userName' of undefined
at Object.eval [as updateRenderer] (ng:///DynamicTestModule/ProfilePersonalInformationComponent.ngfactory.js:72:38)
at Object.debugUpdateRenderer [as updateRenderer] (webpack:///./node_modules/@angular/core/esm5/core.js?:14909:21)
at checkAndUpdateView (webpack:///./node_modules/@angular/core/esm5/core.js?:14023:14)
at callViewAction (webpack:///./node_modules/@angular/core/esm5/core.js?:14369:21)
at execEmbeddedViewsAction (webpack:///./node_modules/@angular/core/esm5/core.js?:14327:17)
at checkAndUpdateView (webpack:///./node_modules/@angular/core/esm5/core.js?:14019:5)
at callViewAction (webpack:///./node_modules/@angular/core/esm5/core.js?:14369:21)
at execEmbeddedViewsAction (webpack:///./node_modules/@angular/core/esm5/core.js?:14327:17)
at checkAndUpdateView (webpack:///./node_modules/@angular/core/esm5/core.js?:14019:5)
at callViewAction (webpack:///./node_modules/@angular/core/esm5/core.js?:14369:21)

To solve above error, I created PerosnalInfoStub class but it didnt work.

component.spec.ts file

describe('ProfilePersonalInformationComponent', () => {
  let component: ProfilePersonalInformationComponent;
  let fixture: ComponentFixture<ProfilePersonalInformationComponent>;
  let personalInfo : PersonalInfo;

  class PersonalInfoStub{
      personalInfo: Subject<any[]> = new Subject<any[]>();



  }

  beforeEach(async(() => {
    TestBed.configureTestingModule({

        imports: [FormsModule, SharedModule, HttpModule, BrowserModule],
      declarations: [ ProfilePersonalInformationComponent ],
      providers: [
        {
           provide: PersonalInfo, useClass: PersonalInfo
        },

        {
            provide: NotificationService, useClass: NotificationService
        },

        {
            provide: LoginService, useClass: LoginService
        },
        {
            provide: ConfigService, useClass: ConfigService
        }

    ],


    })
    .compileComponents();
  }));

  beforeEach(() => {

    fixture = TestBed.createComponent(ProfilePersonalInformationComponent);
    component = fixture.componentInstance;

    fixture.detectChanges();
  });

  it('should create', () => {

    expect(component).toBeTruthy();
  });

personal-info.ts

export class PersonalInfo {
  userName: string;
}

class file of component

ProfilePersonalInformationComponent implements OnInit {




  @Input() personalInfo: PersonalInfo;
  @Input() loadingData;
  savingData: boolean;

  passwordHelpTextArray: string[];
  passwordHelpText: string;
  formErrors: any = {
    username: {
      error: '',
      errorMessage: ''
    },
    currentPassword: {
      error: '',
      errorMessage: ''
    },
    newPassword: {
      error: '',
      errorMessage: ''
    },
    verifyNewPassword: {
      error: '',
      errorMessage: ''
    }
  };

  updatedUsername: string = '';
  existingPassword: string = '';
  newPassword: string = '';
  reEnterNewPassword: string = '';

  constructor(private personalInfoService: PersonalInformationService,
    private notificationService: NotificationService) { }

  ngOnInit(): void {
    this.populateInfo();
  }

  populateInfo() {
    setTimeout(() => {
      if (this.loadingData === false) {
        this.updatedUsername = this.personalInfo.userName;
      } else {
        this.populateInfo();
      }

    }, 500);
  }

Html code for User Name

 <div class="col-sm-2">
        <h3>Username</h3>
        <p>{{personalInfo.userName}}</p>
      </div>
      <div class="col-sm-2">
        <h3>Password</h3>
        <p>********</p>
      </div>
Developer
  • 279
  • 6
  • 22

1 Answers1

0

You should mock component data while testing, especially the @Input properties which will usually get the value from parent component. But in unit testing you will have to mock it by yourself, because no parent component is involved.

beforeEach(() => {
    fixture = TestBed.createComponent(ProfilePersonalInformationComponent);
    component = fixture.componentInstance;
    // mock input data
    component.personalInfo = {"userName" : "XYZ"};
    fixture.detectChanges();
});
Amit Chigadani
  • 28,482
  • 13
  • 80
  • 98