jest修改配置的terminal命令:

npx jest --init

然后在 jest.config.js 文件中查看jest配置

 

jest生成覆盖率报告的terminal命令:

npx jest --coverage

默认报告生成在coverage文件夹

 

匹配器toBe():

toBe()类似于Object.is和===,对象不可用,因为地址不相同

test("测试内容完全一致",() => {
    const a = 6;
    expect(a).toBe(6); 
})

 

匹配器toEqual():

toEqual()类似于==,测试内容相等

test("测试内容相同",() => {
   const a = {one:1 };
   expect(a).toEqual({one:1});//如果用tobe,会因引用地址不同而报错 
})

 

匹配器toBeNull():

检验是否为null

test("测试是否为null",() => {
   const a = null;
   expect(a).toBeNull();  
})

 

匹配器toBeUndefined():

检测是否为undefined

test("测试是否为undefined",() => {
   const a = undefined;
   expect(a).toBeUndefined();  
})

 

匹配器toBeDefined():

检测是否为定义过的值,除undefined外皆pass

test("测试是否为定义的值",() => {
   const a = 1;
   expect(a).toBeDefined();  
})

 

匹配器toBeTruthy():

检测是否为真

test("测试真值",() => {
   const a = true;
   expect(a).toBeTruthy();  
})

 

匹配器toBeFalsy():

检测是否为假

test("检测假值",() => {
   const a = false;
   expect(a).toBeFalsy();  
})

 

匹配器toBeGreaterThan():

比值大

test("比大",() => {
   const count = 1;
   expect(count).toBeGreaterThan(-1);
})

 

匹配器toBeLessThan():

比值小

test("比小",() => {
   const count = 1;
   expect(count).toBeLessThan(2);  
})

 

匹配器toBeCloseTo():

由于js的带小数点数值做运算可能会出现无限小数,所以使用该api避免此情况:

test("避免无穷小数的运算",() => {
   const first = 0.1;
   const second = 0.2;
   expect(first+second).toBeCloseTo(0.3);
})

 

匹配器toMatch():

给出一个字符串a,检测字符串b是否包含在a中

 

test("字符串包含匹配",() => {
   const str = "www.bing.com.cn";
   expect(str).toMatch("bing");  
})

 

 

匹配器toContain():

常用于array和set,检测值是否属于array或set的元素

test("toConatin()",() => {
   const arr = ["a","b","c"];
   const set = new Set(arr); 
   expect(set).toContain("b"); 
})

 

 

匹配器toThrow():

抛出异常

const throwNewErrorFunc = () => {
    throw new Error('this is a new error');
}

test('抛出异常',() => {
    expect(throwNewErrorFunc).toThrow();
})