Jest与Jest Matchers进阶

发布时间: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 对象和数组进行深度比较:
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. 使用 toBeNulltoBeUndefinedtoBeDefinedtoBeTruthy 检查 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. 使用 toBeGreaterThantoBeLessThantoBeGreaterThanOrEqualtoBeLessThanOrEqual 进行数值比较:
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 检查数组或字符串中是否包含特定元素:
test('array contains value', () => {
  expect([1, 2, 3]).toContain(2);
});

test('string contains substring', () => {
  expect('hello world').toContain('world');
});
  1. 使用 toThrowtoThrowError 检查函数是否抛出错误:
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 检查数组或字符串的长度:
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 测试。当然,还有更多其他内置的 Matchers 可供使用。要了解更多关于 Jest 和 Jest Matchers 的信息,请参阅官方文档:https://jestjs.io/docs/getting-started

推荐阅读:
  1. iOS 开发技术栈与进阶
  2. MySQL基础与进阶讲义

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

jest

上一篇:Jest测试中的性能优化建议

下一篇:Jest框架中的setupFilesAfterEnv

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》