首页 > 解决方案 > 在明确定义的属性上“无法读取未定义的属性 X”

问题描述

我正在测试我的fromApi功能:

交易.test.js

// @flow
import Deal from "../src/models/Deal";
import apiProducts from "../__mocks__/api/products";

describe("Deal", () => {
  describe("Deal.fromApi", () => {
    it("takes an api product and returns a Deal", () => {
      const apiDeal = apiProducts[0];
      expect(Deal.fromApi(apiDeal)).toEqual(expectedDeal());
    });
  });
});

交易.js

export default class Deal {
  constructor(obj: Object) {
    console.log("id", obj.id);
    // console.log(obj);

    this.id = obj.id;
    this.name = obj.name;
    this.headline = obj.headline;
    this.fullPrice = obj.fullPrice;
    this.salePrice = obj.salePrice;
    this.photoUrls = obj.photoUrls;
    this.description = obj.description;
    this.address = obj.address;
    this.location = obj.location;
  }

  static fromApi(json: Object): Deal {
    return new Deal(json);
  }
}

测试距离通过还有很长的路要走,因为 api 输入对象有很多属性尚未在构造函数中考虑,但这不是我的问题。

测试在第一行失败:

 ● Deal › Deal.fromApi › takes an api product and returns a Deal

    TypeError: Cannot read property 'id' of undefined

      16 | 
      17 |   constructor(obj: Object) {
    > 18 |     console.log("id", obj.id);
         |                           ^
      19 | 
      20 |     // console.log(obj);
      21 | 

然而控制台打印id就好了!此外,当我记录整个对象时,它按预期记录了整个对象!这一切都在日志语句之前开始,当测试在第一行(this.id = obj.id)失败时,同样的错误只是指向obj不同的地方。

obj不是未定义的。为什么会这样?

更新

当我开始实际充实该fromApi方法时,从一个空的 deal ( const deal = new Deal()) 开始,我在构造函数中得到了一个实际上未定义的obj参数,这显然是当你没有将参数传递给构造函数时会发生的情况。

所以我补充说:

if (!obj) return;

在构造函数的顶部,现在一切正常。

知道这是否真的“解决了”我遇到的“原始”问题,因为那时控制台再次确认这obj不是未定义的。

如果有人可以绕开他们的脑袋告诉我这个问题值得结束,因为它首先是因为错过了一些愚蠢的东西,我对此持开放态度。或者通过指出我缺少的愚蠢的东西来回答它。

标签: javascriptjestjs

解决方案


推荐阅读