[英]Expect a function to change e.g. the length of array
這是一個常見的用例。 我們要測試這個removeItem
function。
// items.js
items = [/* .... */];
function removeItem(id) {
// remove item with given id from `items`
}
我想寫一些類似的東西:
// test.js
expect(() => removeItem(7)).toChange(() => items.length);
我怎么用jest
寫這個?
另一個可能的例子,在 ruby 我們有一個很好的 API :
# test.rb
expect { removeItem(7) }.to(change { items.length }.from(1).to(0))
編輯:當然,我知道以下方法,並且我專門尋找重復較少的東西。
// test.js
expect(items).toHaveLength(1);
removeItem(7);
expect(items).toHaveLength(0);
Jest 保持簡單:
expect(items).toHaveLength(1);
removeItem(7);
expect(items).toHaveLength(0);
可以使用自定義 matcher實現toChange
。
我建議您斷言該數組不應包含id: 7
的 object 。 這樣,在測試失敗的情況下,您可以更好地描述測試失敗的原因
例子:
test('should remove the item from array', () => {
expect(items).not.toContainEqual(
expect.objectContaining({
id: 7
})
)
})
其中,如果發生故障,output 將類似於:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.