【问题标题】:TypeError: Cannot read property 'user' of nullTypeError:无法读取 null 的属性“用户”
【发布时间】:2019-06-30 01:53:10
【问题描述】:

我正在尝试通过我的函数 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);
});

});

【问题讨论】:

  • 如您所写,您的函数不会返回角色。如果this.role 等于字符串admin,它返回一个布尔值。此外,您的测试将函数存根并在其位置调用假函数,因此您的函数实际上从未被调用(因此未测试),这不太可能是您想要的。
  • 您需要模拟 localStorage 才能通过此测试。这是一个例子:medium.com/@armno/…

标签: angular unit-testing


【解决方案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?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-29
    • 2022-01-12
    • 2021-12-04
    • 2021-12-17
    • 2022-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多