.not修饰符允许你测试结果不等于某个值的情况,这和英语的语法几乎完全一样,很好理解。
//functions.test.js
import functions from '../src/functions'
test('sum(2, 2) 不等于 5', () => {
expect(functions.sum(2, 2)).not.toBe(5);
})
.toEqual匹配器会递归的检查对象所有属性和属性值是否相等,所以如果要进行应用类型的比较时,请使用.toEqual匹配器而不是.toBe。
// functions.js
export default {
getAuthor() {
return {
name: 'LITANGHUI',
age: 24,
}
}
}
// functions.test.js
import functions from '../src/functions';
test('getAuthor()返回的对象深度相等', () => {
expect(functions.getAuthor()).toEqual(functions.getAuthor());
})
test('getAuthor()返回的对象内存地址不同', () => {
expect(functions.getAuthor()).not.toBe(functions.getAuthor());
})
.toHaveLength可以很方便的用来测试字符串和数组类型的长度是否满足预期。
// functions.js
export default {
getIntArray(num) {
if (!Number.isInteger(num)) {
throw Error('"getIntArray"只接受整数类型的参数');
}
let result = [];
for (let i = 0, len = num; i < len; i++) {
result.push(i);
}
return result;
}
}
// functions.test.js
import functions from '../src/functions';
test('getIntArray(3)返回的数组长度应该为3', () => {
expect(functions.getIntArray(3)).toHaveLength(3);
})
.toThorw可能够让我们测试被测试方法是否按照预期抛出异常,但是在使用时需要注意的是:我们必须使用一个函数将将被测试的函数做一个包装,正如上面getIntArrayWrapFn所做的那样,否则会因为函数抛出导致该断言失败。
// functions.test.js
import functions from '../src/functions';
test('getIntArray(3.3)应该抛出错误', () => {
function getIntArrayWrapFn() {
functions.getIntArray(3.3);
}
expect(getIntArrayWrapFn).toThrow('"getIntArray"只接受整数类型的参数');
})
.toMatch传入一个正则表达式,它允许我们用来进行字符串类型的正则匹配。
// functions.test.js
import functions from '../src/functions';
test('getAuthor().name应该包含"li"这个姓氏', () => {
expect(functions.getAuthor().name).toMatch(/li/i);
})
测试异步函数
我们调用了expect.assertions(1),它能确保在异步的测试用例中,有一个断言会在回调函数中被执行。这在进行异步代码的测试中十分有效。
使用async和await精简异步代码
test('fetchUser() 可以请求到一个用户名字为Leanne Graham', async () => {
expect.assertions(1);
const data = await functions.fetchUser();
expect(data.name).toBe('Leanne Graham')
})
//toContain匹配对象中是否包含
const arrName = ['liam','jim','bart']
test('匹配对象是否包含',() => {
expect(arrName).toContain('jim')
})
检查一些特殊的值(null,undefined和boolean)
toBeNull 仅匹配 null
toBeUndefined 仅匹配 undefined
toBeDefined 与…相反 toBeUndefined
toBeTruthy匹配if语句视为true的任何内容
toBeFalsy匹配if语句视为false的任何内容
检查数字类型(number)
toBeGreaterThan 大于
toBeGreaterThanOrEqual 至少(大于等于)
toBeLessThan 小于
toBeLessThanOrEqual 最多(小于等于)
toBeCloseTo 用来匹配浮点数(带小数点的相等)
网友评论