[英]Call a static method inside other static method of a class in Javascript
[英]TypeError when testing static method call inside class method
我在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不是一個函數
是否有模擬這種方法或類似方法的正確方法?
應該使用類名稱調用靜態方法。
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>
Static properties are properties of a class, not of an instance of a class.
正如從了解JavaScript中的靜態功能中 qout的
因此,您無需調用淺表。 你可以簡單地
import DeliveryAddressScreen from '../some/path'
it('can call class method', () => {
expect(DeliveryAddressScreen. isAddressReady).toEqual(true)
})
但是!,您正在嘗試在尚未實例化的內容中使用this
內容,因此該內容將不存在
您可以改寫static方法,使其看起來像沒有static關鍵字的樣子
isAddressReady = (address) => {
return true // or false
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.