[英]How to test this statement using jest and enzyme
在我們的代碼中,我有兩個語句
const { column, showTooltip, tooltipValue, data } = props;
const key = column.bindProperties[0].properties[0].name;
在測試中,這給出了錯誤
“TypeError:無法讀取未定義的屬性‘0’。”
這個語句column.bindProperties[0].properties[0].name;
以及如何測試它。
在 JS 中,您不能保證對象具有某些屬性。
當您嘗試訪問column.bindProperties[0].properties[0].name
時, column.bindProperties
或column.bindProperties[0].properties
undefined
- 因此您會遇到錯誤。
您可以使用lodash
的_.get()
或驗證鍵是使用冗余煩人定義的:
const key = column
&& column.bindProperties
&& column.bindProperties[0]
&& column.bindProperties[0].properties
&& column.bindProperties[0].properties[0]
&& column.bindProperties[0].properties[0].name;
這將確保您的代碼不會中斷。 如果未定義鏈中的一個表達式,則表達式將停止計算,您將得到undefined
的結果。
由於沒有人真正把它拼出來,這里有一個可選鏈接的例子:
const key = column?.bindProperties?.[0]?.properties?.[0]?.name;
和無效的合並:
const key = column?.bindProperties?.[0]?.properties?.[0]?.name ?? "I'm a fallback value";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.