【问题标题】:How to test closures with enzyme?如何用酶测试瓶盖?
【发布时间】:2019-12-13 03:10:50
【问题描述】:

我需要测试哪个值会返回闭包。 示例:

onCell = (index) => (row, rowIndex) => ({
    style: { fontWeight: 600 },
    ref: rowIndex === 0 && this.cellRef(index)
  })

我希望回报会是

{ 
    style: { fontWeight: 600 },
    ref: null || this.cellRef(index)
}

【问题讨论】:

  • this 是什么?你为什么要在闭包中捕获它?正如它所写的那样,真的没有办法独立于它定义的代码来测试它......
  • 你的意思是我不能检查什么会返回独立函数????我只是在这个func里传参数,没有独立环境
  • 它不是一个独立的函数。它是一个闭包,它引用了在周围词法范围中定义的值 (this),并且依赖于该值。如果您使用 .cellRef 方法作为参数传递对象,那么它将是。
  • 那么,我该怎么办?

标签: javascript jestjs enzyme


【解决方案1】:

将对象作为参数与索引一起传递给外部函数,而不是使用this。然后,您可以将带有适当返回值的jest.fn() 传递给它,并确保结果是您想要的并且函数被调用:

onCell = (obj, index) => (row, rowIndex) => ({
  style: { fontWeight: 600 },
  ref: rowIndex === 0 && obj.cellRef(index)
});

然后在测试中:

const mock = {
  cellRef: jest.fn(),
};

mock.cellRef.mockReturnValue(true);
const cb = onCell(mock, 5);

等等等等

【讨论】:

    猜你喜欢
    • 2019-08-26
    • 2019-11-15
    • 2020-06-01
    • 2019-04-21
    • 2020-07-15
    • 1970-01-01
    • 2017-05-22
    • 2017-07-03
    • 1970-01-01
    相关资源
    最近更新 更多