【问题标题】:TypeError when testing static method call inside class method测试类方法中的静态方法调用时出现 TypeError
【发布时间】:2018-05-11 22:31:26
【问题描述】:

我在 React 组件中有一个静态方法,例如:

class DeliveryAddressScreen extends Component {
  static isAddressReady(address) {
    return !!(address)
  }

  sendAddress(address) {
    if(this.isAddressReady(address)) {
     // DO SOMETHING
    }

  }
}

我的测试:

  it('sample tests', () => {
    const component = shallow(<DeliveryAddressScreen />)
    component.instance().sendAddress('Address')
    expect(true).toBe(true) // Just a sample
  })

反馈是:

TypeError:this.isAddressReady 不是函数

是否有正确的方法来模拟这种方法或类似的方法?

【问题讨论】:

  • 对于错误,请尝试DeliveryAddressScreen.isAddressReady(...)(相关:js call static method from class)。
  • 是的,只需要在我的类构造函数中添加this.isAddressRead = DeliveryAddressScreen.isAddressReady

标签: javascript reactjs react-native jestjs


【解决方案1】:

应使用类名调用静态方法。

class DeliveryAddressScreen extends React.Component {
  static isAddressReady(address) {
    return !!(address)
  }

  sendAddress(address) {
    if(DeliveryAddressScreen.isAddressReady(address)) {
        console.log(address)
    }
  }
}

const subject = new DeliveryAddressScreen()
subject.sendAddress("test")
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

【讨论】:

    【解决方案2】:
    Static properties are properties of a class, not of an instance of a class.
    

    引用自Understanding static in JavaScript

    因此你不需要调用 shallow。你可以简单地

    import DeliveryAddressScreen from '../some/path'
    it('can call class method', () => {
        expect(DeliveryAddressScreen. isAddressReady).toEqual(true)
    })
    

    但是!!,您正在尝试在尚未实例化的内容中使用 this,因此这将不存在

    你可以重写你的静态方法,而不是像这样没有 static 关键字

    isAddressReady = (address) => {
        return true // or false
     }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-15
      • 1970-01-01
      • 2016-04-23
      • 1970-01-01
      相关资源
      最近更新 更多