Jest 常用匹配器

Jest 常用匹配器

toBe

toBe 使用 Object.is 判断是否严格相等。我理解为精准匹配

test ('测试10与10相匹配',()=>{
  // toBe 匹配引用地址相同
  expect(10).toBe(10)
})

toEqual

toEqual 递归检查对象或数组的每个字段。匹配相同的内容

test ('测试相匹配',()=>{
  const a = {one:1}
  expect(a).toEqual({one:1})
})

not

not 取反;所有的匹配器都可以使用 .not 取反:

test ('not 匹配器',()=>{
  // not 匹配取反
  const a = 1
  // a  不为假
  expect(a).not.toBeFalsy() // 通过
})

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

toBeNull

toBeNull只匹配 null。

test ('测试相匹配null',()=>{
  // toBe 匹配内容相同
  const a = undefind
  expect(a).toBeNull() // 不通过,因为不是null
})

toBeUndefined

toBeUndefined 只匹配 undefined。

test ('测试相匹配undefind',()=>{
  // toBeUndefind 匹配内容相同
  const a = undefind
  expect(a).toBeUndefind() // 通过
})

toBeDefined

toBeDefined只匹配非 undefined。

test ('测试相匹配undefind',()=>{
  // toBeDefind 匹配是否定义过
  const a = undefind
  expect(a).toBeDefind() // 不通过
})

toBeTruthy

toBeTruthy 只匹配真。

test ('测试相匹配toBeTruthy',()=>{
  // toBeTruthy 匹配是否为真
  const a = 1
  expect(a).toBeTruthy() // 通过
})

toBeFalsy

toBeFalsy只匹配假。

test ('测试相匹配toBeFalsy',()=>{
  // toBeFalsy 匹配是否为假
  const a = 1
  expect(a).toBeFalsy() // 不通过
})

toBeGreaterThan

数字匹配器。toBeGreaterThan 实际值大于期望。

//  数字相关的匹配器
test ('toBeGreaterThan',()=>{
  // toBeGreaterThan 匹配 是否更大
  const a = 10
  expect(a).toBeGreaterThan(9) // 通过
})

toBeLessThan

数字匹配器。toBeLessThan 实际值小于期望值

test ('toBeLessThan',()=>{
  // toBeLessThan 匹配 是否更小
  const a = 10
  expect(a).toBeLessThan(11) // 通过
})

toBeLessThanOrEqual

数字匹配器。toBeLessThanOrEqual实际值小于或等于期望值。

test ('toBeGreaterThanOrEqual',()=>{
  // toBeGreaterThanOrEqual 匹配 是否 大于或等于
  // toBeLessThanOrEqual 匹配 是否 小于或等于
  const a = 10
  expect(a).toBeGreaterThanOrEqual(10) // 通过
})

toBeCloseTo

数字匹配器。toBeCloseTo比较浮点数的值,避免误差。对于比较浮点数的相等,应该使用 toBeCloseTo

test ('toBeCloseTo',()=>{
  // toBeCloseTo 匹配 是否 等于
  // 计算浮点数 就用这种
  const firstName = 0.1
  const secondName = 0.3
  expect(firstName + secondName).toEqual(0.4) // 不通过
  expect(firstName + secondName).toBeCloseTo(0.4) // 通过
})

toMatch

字符串匹配器。toMatch 正则匹配。

// 和string相关
test ('toMatch',()=>{
  // toMatch 匹配 字符串是否包含
  const str = 'http://www.dell-lee.com'
  expect(str).toMatch('dell') // 通过
  expect(str).toMatch(/dell-lee/) // 通过  正则也可以
})

test('there is no I in team', () => {
  expect('team').not.toMatch(/I/);
});

test('but there is a "stop" in Christoph', () => {
  expect('Christoph').toMatch(/stop/);
});

toHaveLength(number)

- 判断一个有长度的对象的长度

expect([1, 2, 3]).toHaveLength(3);
expect('abc').toHaveLength(3);
expect('').not.toHaveLength(5);

toContain(item)

数组匹配器。toContain判断数组中是否包含指定项。

// Array ,Set
test ('toContain',()=>{
  // toContain 匹配 数组是否包含
  const str = ['dell','lee','imooc']
  expect(str).toContain('dell') // 通过

  // 写法2
  const str = ['dell','lee','imooc']
  const data = new Set(str)
  expect(data).toContain('dell') // 通过

})

const shoppingList = [
  'diapers',
  'kleenex',
  'trash bags',
  'paper towels',
  'beer',
];

test('购物清单(shopping list)里面有啤酒(beer)', () => {
  expect(shoppingList).toContain('beer');
});

toContainEqual(item)

数组匹配器。- 判断数组中是否包含一个特定对象,类似 toEqual 与 toContain 的结合

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

toMatchObject(object)

判断一个对象嵌套的 key 下面的 value 类型,需要传入一个对象。

const houseForSale = {
  bath: true,
  bedrooms: 4,
  kitchen: {
    amenities: ['oven', 'stove', 'washer'],
    area: 20,
    wallColor: 'white',
  },
};
const desiredHouse = {
  bath: true,
  kitchen: {
    amenities: ['oven', 'stove', 'washer'],
    wallColor: expect.stringMatching(/white|yellow/),
  },
};

test('the house has my desired features', () => {
  expect(houseForSale).toMatchObject(desiredHouse);
});

toHaveProperty(keyPath, value)

对象匹配器。toHaveProperty(keyPath, value) 判断对象中是否包含指定属性。

// Object containing house features to be tested
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');

  // Deep referencing using an array containing the keyPath
  expect(houseForSale).toHaveProperty(['kitchen', 'area'], 20);
  expect(houseForSale).toHaveProperty(
    ['kitchen', 'amenities'],
    ['oven', 'stove', 'washer'],
  );
  expect(houseForSale).toHaveProperty(['kitchen', 'amenities', 0], 'oven');

  expect(houseForSale).not.toHaveProperty(['kitchen', 'open']);
});

// demo.js
 <View
        className="navigation-bar"
        style={{
          height: `${utils.navHeight}px`,
          color,
          backgroundColor
        }}
      >
</View>

// demo.test.js
  const navBackEle = wrapper.find('.navigation-bar'); // 主体颜色配置
	expect(navBackEle.prop('style')).toHaveProperty('backgroundColor', '#32cb9d');

toBeInstanceOf

toBeInstanceOf 判断对象是否是某个类的实例,底层使用 instanceof。


toThrow

toThrow 判断是否抛出指定的异常。

//  异常情况的匹配

const throwNewErrorFunc = ()=>{
  throw new Error('this is a new error')
}
test ('toThrow',()=>{
  // toThrow 匹配 是否异常
  expect(throwNewErrorFunc).toThrow() // 通过
  expect(throwNewErrorFunc).not.toThrow() // 不通过
  expect(throwNewErrorFunc).toThrow('this is a new error') // 通过
  expect(throwNewErrorFunc).toThrow(/this is a new error/) // 通过
})

toHaveBeenCalled()

- 用来判断一个函数是否被调用过

toHaveBeenCalled() 也有个别名是.toBeCalled(),用来判断一个函数是否被调用过。

describe('drinkAll', () => {
  test('drinks something lemon-flavored', () => {
    const drink = jest.fn();
    drinkAll(drink, 'lemon');
    expect(drink).toHaveBeenCalled();
  });

  test('does not drink something octopus-flavored', () => {
    const drink = jest.fn();
    drinkAll(drink, 'octopus');
    expect(drink).not.toHaveBeenCalled();
  });
});

toHaveBeenCalledTimes(number)

和 toHaveBeenCalled 类似,判断函数被调用过几次。

test('drinkEach drinks each drink', () => {
  const drink = jest.fn();
  drinkEach(drink, ['lemon', 'octopus']);
  expect(drink).toHaveBeenCalledTimes(2);
});

toHaveBeenCalledWith(ecent)

事件调用的时候,他的参数

  describe('Zero', () => {
    it('calls setCount with 0', () => {
      wrapper.find('#zero-count').props().onClick();
      expect(setState).toHaveBeenCalledWith(0);
    });
  });

toHaveBeenLastCalledWith

最后一次调用时,函数的参数匹配

describe('TripTypeChoose组件测试', () => {
  it('展示TripTypeChoose', () => {
    const propsEvent = jest.fn();
    const value = '1';
    const wrapper = shallow(<TripTypeChoose handelTicketChoice={propsEvent} singleTrip="0" formOrder={true} />);
    wrapper.find('[data-test="handelTicketDom"]').simulate('change', {
      detail: { value },
    });
    // 断言 change 事件参数为value
    expect(propsEvent).toHaveBeenLastCalledWith(value);


    expect(toJson(wrapper)).toMatchSnapshot();
  });
});

lastCalledWith

toBeCalledWith

toBeInstanceOf

toMatchSnapshot

toThrowError

toThrowErrorMatchingSnapshot

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值