JEST断言库(常用api)

Expect

当你写测试,你经常需要检查值满足一定的条件。expect 可以访问一些“匹配器”来判断是否能够通过验证 如:

test('first use expect', function () {
  expect(1 + 1).toBe(2);
});

expect.extend

我们可以expect.extend扩展自己编写的函数 如:

expect.extend({
  toNaN(received, argument) {
    if (isNaN(received)) {
      return {
        message: () => (
          `expected ${received} is NaN`
        ),
        pass: true,
      };
    } else {
      return {
        message: () => (
          `expected ${received} not NaN`
        ),
        pass: false,
      };
    }
  },
});

test('even and odd numbers', () => {
  expect('d').toNaN();
});

.not

.not可以测试相反的东西 

test('.not', () => { expect(1 + 1 ).not.toBe(3); });

.toBe(value)

可以用来断言你expect的值 

const Dog = { name: 'hasiqi', age: 1, };
describe('Dog', () => {
  test('name', () => {
    expect(Dog.name).toBe('hasiqi');
  });

  test('age', () => {
    expect(Dog.age).toBe(1);
  });
});

.toEqual(value)

使用.toEqual时要检查两个对象具有相同的值。该匹配器递归地检查所有字段的相等性,而不是检查对象的身份-这也称为“深度相等” 如:

const can1 = {
  flavor: 'grapefruit',
  ounces: 12,
};
const can2 = {
  flavor: 'grapefruit',
  ounces: 12,
};

describe('the La Croix cans on my desk', () => {
  test('have all the same properties', () => {
    expect(can1).toEqual(can2);
  });
  test('are not the exact same can', () => {
    expect(can1).not.toBe(can2);
  });
});

 

.toHaveBeenCalled()

用于判断你的函数是否有被调用 function callFn(fn, name) { if (name === 'octopus') { fn() } }

test('toHaveBeenCalled', () => {
  const fn = jest.fn();
  callFn(fn, 'octopus');
  expect(fn).toHaveBeenCalled();
});
复制代码

.toBeDefined()

用户判断默认变量是否已经被定义 或者可以用来判断函数有返回值 如:

function testTobeDefined() {
  return {}
}
test('toBeDefined', () => {
  const a = '1';
  expect(a).toBeDefined();
  expect(window.b).not.toBeDefined();
  expect(testTobeDefined()).toBeDefined();
});
复制代码

toBeUndefined()

和toBeDefined 相反

.toBeFalsy

.toBeFalsy当您不在乎值是什么时使用,只需要确保在布尔上下文中值是假(false, 0, '', null, underfined, NaN) 如:

function testToBeFalsy() {
  return false;
}
function testToBeTrue() {
  return true;
}
test('toBeFalsy', () => {
  expect(testToBeFalsy()).toBeFalsy();
  expect(testToBeTrue()).not.toBeFalsy();
});
复制代码

.toBeTruthy()

和toBeFalsy相反

toBeGreaterThan

可用于判断是指的大小,不包括等于 如: function ouncesPerCan() { return 11; }

test('ounces per can is more than 10', () => {
  expect(ouncesPerCan()).toBeGreaterThan(10);
});
复制代码

toBeGreaterThanOrEqual

大于等于

.toBeLessThan

小于

.toBeLessThanOrEqual

小于等于

.toBeInstanceOf(Class)

用于判断某个对象是否集成于默认构造函数 如: class A {}

expect(new A()).toBeInstanceOf(A);
expect(() => {}).toBeInstanceOf(Function);
expect(new A()).toBeInstanceOf(Function)
复制代码

.toBeNull()

.toBeNull() is the same as .toBe(null)

.toContain(item)

用于断言list中是否包含某个item

// toContain
test('toContain', () => {
  expect(['item', 'item2']).toContain('item');
});
复制代码

.toContainEqual(item)

用于断言list中是否包含某个item, 此匹配器递归地检查所有字段的相等性,而不是检查对象标识

test('is delicious and not sour', () => { 
const myBeverage = {delicious: true, sour: false};
expect([{delicious: true, sour: false}, {delicious: true, sour: true, age: 1}])
.toContainEqual(myBeverage); });

.resolves

可以用来测试promise resolve的值 如:

test('resolves to lemon', async () => {
  await expect(Promise.resolve('lemon')).resolves.toBe('lemon');
  await expect(Promise.resolve('lemon')).resolves.not.toBe('octopus');
});
复制代码

.rejects

可以用来测试promise rejects的值 如:

test('rejects to lemon', async () => {
  await expect(Promise.rejects('lemon')).rejects.toBe('lemon');
  await expect(Promise.rejects('lemon')).rejects.not.toBe('octopus');
});    
复制代码

.toHaveLength(number)

判断object 的length值 如:

expect([1, 2, 3]).toHaveLength(3);
expect('abc').toHaveLength(3);
复制代码

.toMatch(regexpOrString)

匹配某个正则

expect('grapefruit111').toMatch(/grapefruit/); 
expect('grapefruit111').toMatch(new RegExp('grapefruit'));

.toHaveProperty(keyPath, value)

去判断某个对象是否有某个属性 以及判断它的属性值 如:

const houseForSale = {
  bath: true,
  bedrooms: 4,
  kitchen: {
    amenities: ['oven', 'stove', 'washer'],
    area: 20,
    wallColor: 'white',
  },
};

test('this house has my desired features', () => {
  // Simple Referencing
  expect(houseForSale).toHaveProperty('bath');
  expect(houseForSale).toHaveProperty('bedrooms', 4);

  expect(houseForSale).not.toHaveProperty('pool');

  // Deep referencing using dot notation
  expect(houseForSale).toHaveProperty('kitchen.area', 20);
  expect(houseForSale).toHaveProperty('kitchen.amenities', [
    'oven',
    'stove',
    'washer',
  ]);

  expect(houseForSale).not.toHaveProperty('kitchen.open');
});
复制代码

.toThrow(error)

用于判断函数抛出的错误 如:

function drinkFlavor(flavor: string) {
  if (flavor == 'octopus') {
    throw new Error('yuck, octopus flavor');
  }
  // Do some other stuff
}
test('throws on octopus', () => {
  function drinkOctopus() {
    drinkFlavor('octopus');
  }

  // Test the exact error message
  expect(drinkOctopus).toThrowError('yuck, octopus flavor');

  // Test that the error message says "yuck" somewhere
  expect(drinkOctopus).toThrowError(/yuck/);

});
  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值