简体   繁体   中英

Angular unit testing. TypeError: Cannot read property 'id' of null. [Jasmine, Karma]

I am writing a component unit tests for my Angular application. I have a currentUser variable i am using in my component as well as html template. It is been mocked (hardcoded via component.currentUser = {...} ) on every test. Anyway, Karma fails. Would appreciate any help.

UserProfileComponent > should create
TypeError: Cannot read property 'id' of null
    at UserProfileComponent.ngOnInit (http://localhost:9877/_karma_webpack_/webpack:/src/app/modules/user-profile/page/user-profile/user-profile.component.ts:4:21)
    at callHook (http://localhost:9877/_karma_webpack_/webpack:/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:2573:1)
    at callHooks (http://localhost:9877/_karma_webpack_/webpack:/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:2542:1)
    at executeInitAndCheckHooks (http://localhost:9877/_karma_webpack_/webpack:/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:2493:1)
    at refreshView (http://localhost:9877/_karma_webpack_/webpack:/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:9481:1)
    at renderComponentOrTemplate (http://localhost:9877/_karma_webpack_/webpack:/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:9580:1)
    at tickRootContext (http://localhost:9877/_karma_webpack_/webpack:/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:10811:1)
    at detectChangesInRootView (http://localhost:9877/_karma_webpack_/webpack:/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:10836:1)
    at RootViewRef.detectChanges (http://localhost:9877/_karma_webpack_/webpack:/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:22815:1)
    at ComponentFixture._tick (http://localhost:9877/_karma_webpack_/webpack:/node_modules/@angular/core/__ivy_ngcc__/fesm2015/testing.js:141:1)

Code example below.

user-profile.component.ts

ngOnInit(): void {
    this.currentUser = this.userService.getUser();
    console.log(this.currentUser.id);
    this.userAnnouncements();
  }

user-profile.component.spec.ts

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

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      imports: [HttpClientTestingModule, RouterTestingModule],
      declarations: [UserProfileComponent],
      schemas: [CUSTOM_ELEMENTS_SCHEMA],
    }).compileComponents();
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(UserProfileComponent);
    component = fixture.componentInstance;
    component.currentUser = {
      id: 1,
      email: 'admin@admin.com',
      firstname: 'admin',
      img_name: 'photo',
      lastname: 'admin',
      location: 1,
      password: 'hashed_pass',
      role: 'admin',
      username: 'admin',
    };
    fixture.detectChanges();
  });

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

Problem is that you have not mocked the data for userService , hence it overrides the value you are setting.

You should mock the service as below:

describe('UserProfileComponent', () => {
  let component: UserProfileComponent;
  let fixture: ComponentFixture<UserProfileComponent>;
  let userService: jasmine.SpyObj<UserService>;
  beforeEach(async () => {
    const userServiceSpy = jasmine.createSpyObj('UserService', ['getUser']);
    await TestBed.configureTestingModule({
      imports: [HttpClientTestingModule, RouterTestingModule],
      declarations: [UserProfileComponent],
      providers: [ {provide: UserService, useValue: userServiceSpy }],
      schemas: [CUSTOM_ELEMENTS_SCHEMA],
    }).compileComponents();
  });

  beforeEach(() => {
    userService = TestBed.inject(UserService) as jasmine.SpyObj<UserService>;
    userService.getUser.and.returnValue({
      id: 1,
      email: 'admin@admin.com',
      firstname: 'admin',
      img_name: 'photo',
      lastname: 'admin',
      location: 1,
      password: 'hashed_pass',
      role: 'admin',
      username: 'admin',
    });
    fixture = TestBed.createComponent(UserProfileComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
    expect(component.currentUser.id).toBe(1)
  });
});

I would recommend you to read the collection of articles to know how to unit test with well defined practice

There is a pretty easy way to fix this issue: You can do the following:

// In your service file, do this: 

@Injectable() 
class MockUserService extends UserService {
  getUser() {
    const mockData = {
      id: 1,
      email: 'admin@admin.com',
      firstname: 'admin',
      img_name: 'photo',
      lastname: 'admin',
      location: 1,
      password: 'hashed_pass',
      role: 'admin',
      username: 'admin',
    };
    
    return mockData;
  }

  // You can add more methods your service provides and mock here
}


describe('UserProfileComponent', () => {
  let component: UserProfileComponent;
  let fixture: ComponentFixture<UserProfileComponent>;
  beforeEach(async () => {
    await TestBed.configureTestingModule({
      imports: [HttpClientTestingModule, RouterTestingModule],
      declarations: [UserProfileComponent],
      providers: [{
         provide: UserService, 
         useClass: MockUserService 
      }],
      schemas: [CUSTOM_ELEMENTS_SCHEMA],
    }).compileComponents();
  });

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

  it('should create', () => {
    expect(component).toBeTruthy();
    expect(component.currentUser.id).toBe(1)
  });

  it('should run #ngOnInit() method', () => {
     spyOn(component, 'ngOnInit').and.callThrough();
     component.ngOnInit();
     expect(component.ngOnInit).toHaveBeenCalled(); 
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM