溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Jest與Jest Matchers進階

發(fā)布時間:2024-08-28 10:50:05 來源:億速云 閱讀:82 作者:小樊 欄目:編程語言

Jest 是一個流行的 JavaScript 測試框架,它可以輕松地為你的項目編寫和管理測試

  1. 使用 toBenot.toBe 進行基本斷言:
test('two plus two is four', () => {
  expect(2 + 2).toBe(4);
});

test('two plus two is not five', () => {
  expect(2 + 2).not.toBe(5);
});
  1. 使用 toEqual 對象和數(shù)組進行深度比較:
test('objects have the same properties and values', () => {
  const obj1 = { a: 1, b: 2 };
  const obj2 = { a: 1, b: 2 };
  expect(obj1).toEqual(obj2);
});
  1. 使用 toBeNull、toBeUndefinedtoBeDefinedtoBeTruthy 檢查 null、undefined 和布爾值:
test('null is null', () => {
  expect(null).toBeNull();
});

test('undefined is undefined', () => {
  expect(undefined).toBeUndefined();
});

test('a defined value is defined', () => {
  expect(42).toBeDefined();
});

test('a truthy value is truthy', () => {
  expect(42).toBeTruthy();
});
  1. 使用 toBeFalsy 檢查假值:
test('zero is falsy', () => {
  expect(0).toBeFalsy();
});
  1. 使用 toBeGreaterThan、toBeLessThan、toBeGreaterThanOrEqualtoBeLessThanOrEqual 進行數(shù)值比較:
test('pi is greater than 3', () => {
  expect(Math.PI).toBeGreaterThan(3);
});

test('pi is less than 4', () => {
  expect(Math.PI).toBeLessThan(4);
});

test('pi is greater than or equal to 3', () => {
  expect(Math.PI).toBeGreaterThanOrEqual(3);
});

test('pi is less than or equal to 4', () => {
  expect(Math.PI).toBeLessThanOrEqual(4);
});
  1. 使用 toContain 檢查數(shù)組或字符串中是否包含特定元素:
test('array contains value', () => {
  expect([1, 2, 3]).toContain(2);
});

test('string contains substring', () => {
  expect('hello world').toContain('world');
});
  1. 使用 toThrowtoThrowError 檢查函數(shù)是否拋出錯誤:
test('function throws an error', () => {
  const myFunction = () => {
    throw new Error('This is an error');
  };
  expect(myFunction).toThrow();
  expect(myFunction).toThrowError('This is an error');
});
  1. 使用 toHaveLength 檢查數(shù)組或字符串的長度:
test('array has length of 3', () => {
  expect([1, 2, 3]).toHaveLength(3);
});

test('string has length of 5', () => {
  expect('hello').toHaveLength(5);
});
  1. 使用 toHaveProperty 檢查對象是否具有特定屬性:
test('object has property', () => {
  const obj = { a: 1, b: 2 };
  expect(obj).toHaveProperty('a');
  expect(obj).toHaveProperty('b', 2);
});
  1. 使用 toMatch 和正則表達式進行字符串匹配:
test('string matches pattern', () => {
  expect('hello world').toMatch(/world/);
});

這些 Jest Matchers 可以幫助你更輕松地編寫和管理 JavaScript 測試。當(dāng)然,還有更多其他內(nèi)置的 Matchers 可供使用。要了解更多關(guān)于 Jest 和 Jest Matchers 的信息,請參閱官方文檔:https://jestjs.io/docs/getting-started

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI