【问题标题】:jasmine testing against localstorage with angular茉莉花测试本地存储与角度
【发布时间】:2022-07-22 22:20:42
【问题描述】:

我试图弄清楚我的测试失败的原因。当页面加载时,从构造函数中的 localstorage 中获取一个值,并在调用方法 sortItems 之后

  constructor(private loadingCtrl: LoadingController) {

                this.details = JSON.parse(localStorage.getItem('details'));

                this.sortItems('id')

              }

  sortItems(value) {
    if (value === 'id') {
      this.details.items = this.details.items.sort((a, b) =>
      a.id > b.id ? 1 : b.id > a.id ? -1 : 0
    );
   }

   if (value === 'name') {
    this.details.items = this.details.items.sort((a, b) =>
    a.name > b.name ? 1 : b.name > a.name ? -1 : 0
  );

 }
  }

我的茉莉花测试用例如下

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

我在文件中有模拟数据的地方

const order = {
        first_name: 'Michele T',
        id: 41861,
        items: [{
            id: 135878,
            name: 'Arden',
            status: 'active'
        }],
    };

const mockLocationArray = [order];

export { order, mockLocationArray };

当我运行ng test 时,我收到错误Cannot read properties of null (reading 'items'),但项目已在测试用例中定义

【问题讨论】:

    标签: angular jasmine


    【解决方案1】:

    当页面加载时,在构造函数中从本地存储中抓取一个值,并且在调用方法 sortItems 之后

    我猜这个组件是在你的beforeEach() 中创建的(或者实际上没有创建,因为它失败了),比如fixture = TestBed.createComponent(MyComponent)。它正在尝试创建组件,构造函数运行,尝试从 localStorage 访问 details,但什么也没找到,sortItems 尝试对未定义进行排序,然后您会收到错误消息。这一切甚至在您的“应该创建”运行之前就已经发生了。

    一种解决方案是模拟 localStorage,并在创建组件之前执行此操作。这是一个关于在 Jasmine 中模拟 localStorage 的线程: How to mock localStorage in JavaScript unit tests?

    【讨论】:

      猜你喜欢
      • 2017-05-02
      • 2022-01-19
      • 2020-08-19
      • 2016-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多