【问题标题】:react-testing-library Mocking Fat Arrow Component Methodsreact-testing-library Mocking Fat Arrow 组件方法
【发布时间】:2020-01-31 18:58:01
【问题描述】:

我正在尝试创建一个单元测试来测试带有粗箭头函数方法的 React 组件。我试图通过 react-testing-library + jest 在单元测试中模拟这些方法,但没有成功

我无法进行模拟,因为 jest.spyOn 会抛出一个错误,指出该方法不是函数

【问题讨论】:

  • 你能把它转换成非=>函数吗?
  • 需要示例
  • 当然,将类中的方法转换为常规语法,使用 Prototype 可以很容易地窥探它们。否则我的愿望是坚持现有代码,而不是重构并再次使用 .bind 方法:) 示例(粗箭头):testMethod = () => this.props.testMethod('test') 示例(常规):constructor() { this.testMethod = this.testMethod.bind(); } testMethod() {return this.props.testMethod('test');}

标签: reactjs jestjs react-testing-library


【解决方案1】:

这打破了 react-testing-library 背后的封装理念。你不应该关心模拟内部方法;相反,专注于用户可以观察到的 UI 变化,并针对这些变化进行测试。

查看文档中的 Guiding Principles 了解更多上下文。

【讨论】:

    猜你喜欢
    • 2020-06-12
    • 2019-06-14
    • 2021-06-02
    • 2019-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-10
    • 1970-01-01
    相关资源
    最近更新 更多