我在React Component中有一个静态方法,如:
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不是函数
有没有正确的方法来模拟这种方法或类似的东西?
答案 0 :(得分:2)
应使用类名调用静态方法。
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>
答案 1 :(得分:0)
Static properties are properties of a class, not of an instance of a class.
从Understanding static in JavaScript中退出
因此,您无需调用浅表。您可以简单地
import DeliveryAddressScreen from '../some/path'
it('can call class method', () => {
expect(DeliveryAddressScreen. isAddressReady).toEqual(true)
})
但是!,您正在尝试在尚未实例化的内容中使用this
,因此该内容将不存在
您可以改写静态方法,使其看起来像没有static关键字的
isAddressReady = (address) => {
return true // or false
}