您好,登錄后才能下訂單哦!
Jest 是一個流行的 JavaScript 測試框架,它可以輕松地為你的項目編寫和管理測試
toBe
和 not.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);
});
toEqual
對象和數組進行深度比較:test('objects have the same properties and values', () => {
const obj1 = { a: 1, b: 2 };
const obj2 = { a: 1, b: 2 };
expect(obj1).toEqual(obj2);
});
toBeNull
、toBeUndefined
、toBeDefined
和 toBeTruthy
檢查 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();
});
toBeFalsy
檢查假值:test('zero is falsy', () => {
expect(0).toBeFalsy();
});
toBeGreaterThan
、toBeLessThan
、toBeGreaterThanOrEqual
和 toBeLessThanOrEqual
進行數值比較: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);
});
toContain
檢查數組或字符串中是否包含特定元素:test('array contains value', () => {
expect([1, 2, 3]).toContain(2);
});
test('string contains substring', () => {
expect('hello world').toContain('world');
});
toThrow
和 toThrowError
檢查函數是否拋出錯誤:test('function throws an error', () => {
const myFunction = () => {
throw new Error('This is an error');
};
expect(myFunction).toThrow();
expect(myFunction).toThrowError('This is an error');
});
toHaveLength
檢查數組或字符串的長度:test('array has length of 3', () => {
expect([1, 2, 3]).toHaveLength(3);
});
test('string has length of 5', () => {
expect('hello').toHaveLength(5);
});
toHaveProperty
檢查對象是否具有特定屬性:test('object has property', () => {
const obj = { a: 1, b: 2 };
expect(obj).toHaveProperty('a');
expect(obj).toHaveProperty('b', 2);
});
toMatch
和正則表達式進行字符串匹配:test('string matches pattern', () => {
expect('hello world').toMatch(/world/);
});
這些 Jest Matchers 可以幫助你更輕松地編寫和管理 JavaScript 測試。當然,還有更多其他內置的 Matchers 可供使用。要了解更多關于 Jest 和 Jest Matchers 的信息,請參閱官方文檔:https://jestjs.io/docs/getting-started
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。