TypeError:无法读取null的属性“ user”

时间:2019-02-06 06:50:51

标签: angular unit-testing

我正在尝试通过我的函数isAdmin()的单元测试。该函数应该只返回一个角色。它说“用户”无法读取,因为我已经从.ts文件中currentUser提供的信息中扮演了角色。我不确定如何在我的测试代码(.spec.ts)文件中传递用户信息。

TypeError:无法读取null的属性“用户”

list-user.component.ts

constructor(public auth: AuthenticationService, public router: Router, public dialog: MatDialog) { }

ngOnInit() {
    const currentUser = JSON.parse(localStorage.getItem('currentUser')).user;
    this.role = currentUser.role;
}

isAdmin() {
    return this.role.toLowerCase() === 'admin';
  }

list-user.component.spec.ts

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { ListUserComponent } from './list-user.component';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { CustomMaterialModule } from 'src/app/core/material.module';
import { HttpClientModule } from '@angular/common/http';
import { RouterTestingModule } from '@angular/router/testing';
import { from } from 'rxjs';

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

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ ListUserComponent ],
      imports: [
        FormsModule,
        ReactiveFormsModule,
        CustomMaterialModule,
        HttpClientModule,
        RouterTestingModule
    ]
    })
    .compileComponents();
  }));

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



it('should call isAdmin()', () => {

  let role = 'admin'
  spyOn(component, 'isAdmin').and.callFake(() => {
    return from([role]);
  });
  component.isAdmin();
  expect(component.role).toBe(role);
});

});

1 个答案:

答案 0 :(得分:1)

它可能是null,因为localStorage可能尚未用currentUser键初始化。因此,您需要检查使用currentUser键的值是否存在

ngOnInit() {
    const currentUser = JSON.parse(localStorage.getItem('currentUser'));
    this.role = currentUser ? currentUser.user.role : DEFAULT_ROLE; // You have to define a default role
}

更新

而且,正如@DeWetvan如评论中所述,您需要在单元测试时模拟localStorage

示例:How to mock localStorage in JavaScript unit tests?