簡體   English   中英

如何使用玩笑和酶來測試這個陳述

[英]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.bindPropertiescolumn.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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM