網站搜尋

typescript - 有沒有一個 jest 匹配器像 toEqual 一樣工作,但將 null 和 undefined 視為相等的值?


我有一個 API,它不會省略對於「空」值(null、none、nil)的欄位的 JSON 序列化,並且會把所有這些欄位都返回為 "fieldName": null。我在測試程式碼(TypeScript)中定義了 DTO 類型,我希望將這些欄位設為可選(?)並在很多地方保持 undefined。不幸的是,jest 的 toEqual() 將 undefined(測試程式碼中的值)和 null(API 返回的值)視為不同的值。我目前的解決方案是使用聯合類型,比如 string | null,但這相當冗長,因為我必須總是初始化這些欄位。我查閱了 jest 的參考資料,沒有找到現成的解決方案。所以,創建自定義 matcher 是解決這個問題的唯一方法嗎?注意:我無法更改 API 的序列化策略。

答案#1

expect(null).toBe(undefined) 失敗了!

基本上你遇到的情況是,有時在評估一個物件之後,你在一邊會得到 null,而在另一邊會得到 undefined

我試過使用其他 jest 方法如 toEqual,但就是不起作用。

我的解決方案

expect(null == undefined).toBe(true)

答案#2

使用 jest-extended(由 Jest 社群維護的額外 Jest 匹配器)你可以使用 toBeNil():

在檢查一個值是 null 或 undefined 時使用 .toBeNil。

test('passes when value is null or undefined', () => {
  expect(null).toBeNil()
  expect(undefined).toBeNil()
  expect(true).not.toBeNil()
})

請參見:https://github.com/jest-community/jest-extended#tobenil