【问题标题】:Jest - TypeError: Cannot read property '[object Array]' of undefined开玩笑-TypeError:无法读取未定义的属性“[object Array]”
【发布时间】:2020-07-10 14:59:34
【问题描述】:

我开玩笑地写了一个单元测试,运行它时看到这个错误。我在控制台中获得了正确的数据。我已经查看了与我类似的这些帖子,但仍然不明白为什么会这样:

这是我的测试:

import filterAvailableSlots from './filterAvailableSlots';

/* UNIT TEST */

describe('filterAvailableSlots', () => {
  it('should return an array', async () => {
    const bookedSlots = { '10:30': true, '11:00': true };
    const allSlots = ['9:30', '10:00', '10:30', '11:00', '11:30', '12:00'];
    const availableSlots = filterAvailableSlots([allSlots, bookedSlots]);
    expect(Array.isArray(availableSlots)).toBe(true);
  });
});

这是我的代码:

/**
 * @param {Array} allSlots
 * @param {Object} bookedSlots
 * @return an array of available slots
 */

export default function filterAvailableSlots(allSlots, bookedSlots) {
  let availableSlots = [];
  availableSlots = allSlots.filter((item) => !bookedSlots[item]);
  return availableSlots;
}

应该过滤一个时间数组,并删除任何匹配一个bookedSlots对象键的项目。

更多错误细节的图片:

doesn't like my reference to the object property

正确的返回值,我可以通过 console.log 正确看到:

[ '9:30', '10:00', '11:30', '12:00' ] 

一定是我不理解的 Javascript 怪癖。即使我在控制台中看到正确的数据,任何人都知道为什么测试失败了吗?

【问题讨论】:

    标签: javascript arrays jestjs javascript-objects


    【解决方案1】:

    改变

    const availableSlots = filterAvailableSlots([allSlots, bookedSlots]);
    

    const availableSlots = filterAvailableSlots(allSlots, bookedSlots);
    

    另外,函数中最初的let 语句没有做任何事情。我只想写这个:

    export default function filterAvailableSlots(allSlots, bookedSlots) {
      return allSlots.filter((item) => !bookedSlots[item]);
    }
    

    【讨论】:

    • 谢谢!当然是打错字了,看久了就瞎了。快把我逼疯了!
    猜你喜欢
    • 2020-11-19
    • 2018-06-17
    • 1970-01-01
    • 2023-03-03
    • 2017-12-15
    • 2020-06-26
    • 2017-10-18
    • 2022-01-18
    • 2019-08-08
    相关资源
    最近更新 更多