3

I have a static method inside a React Component, like:

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

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

  }
}

And my test:

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

the feedback is:

TypeError: this.isAddressReady is not a function

Is there a right way to mock this method or something like that?

skyboyer
  • 22,209
  • 7
  • 57
  • 64
Eduardo Pedroso
  • 839
  • 3
  • 12
  • 30
  • 2
    For the error, try `DeliveryAddressScreen.isAddressReady(...)` (related: [js call static method from class](https://stackoverflow.com/questions/43614131/js-call-static-method-from-class/43614217)). – Jonathan Lonowski May 11 '18 at 22:34
  • 1
    Yeah, just needed to add `this.isAddressRead = DeliveryAddressScreen.isAddressReady` to my class constructor – Eduardo Pedroso May 17 '18 at 14:15

2 Answers2

2

A static method should be called with the class name.

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>
Sing
  • 3,942
  • 3
  • 29
  • 40
1
Static properties are properties of a class, not of an instance of a class.

As qouted from Understanding static in JavaScript

Therefore you not need to call shallow. You can simply

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

However!!, you are trying to use this inside of something that has not been instantiated and therefore this will not exist

You could rewrite your static method instead to look like this without the static keyword

isAddressReady = (address) => {
    return true // or false
 }
Cody Elhard
  • 655
  • 1
  • 7
  • 17