Jest 新手入门笔记

1. 匹配器 Matchers

test('two plus two is four', () => {
    expect(2 + 2).toBe(4);
});
复制代码

test() 别名 it()javascript

expect(...).not.toBe(...) 测试相反的匹配java

普通匹配器

  • toBe 使用的是Object.is()判断两个值是否相等, 若是判断object的话要使用toEqual代替。android

  • toEqual 递归检查对象或数组的每一个字段。ios

  • toBeNull 只匹配 null正则表达式

  • toBeUndefined 只匹配 undefinedjson

  • toBeDefinedtoBeUndefined 相反axios

  • toBeTruthy 匹配任何 if 语句为真数组

  • toBeFalsy 匹配任何 if 语句为假promise

数字:

  • toBeGreaterThan 大于
  • toBeGreaterThanOrEqual 大于等于
  • toBeLessThan 小于
  • toBeLessThanOrEqual 小于等于
  • toBeCloseTo 比较浮点数相等,忽略舍入偏差

字符串:

  • toMatch 使用正则表达式匹配字符串
  • toContain 检查数组或可迭代对象是否包含某个特定选项
test('there is no I in team', () => {
    expect('team').not.toMatch(/I/)
})
复制代码

测试异常toThrow

function compileAndroidCode(){
    throw new Error('you are using the wrong JDK');
}

test('compiling android goes as expected', () => {
    expect(compileAndroidCode).toThrow();
    expect(compileAndroidCode).toThrow(Error);
    // You can also use the exact error message or a regexp
    expect(compileAndroidCode).toThrow('you are using the wrong JDK');
    expect(compileAndroidCode).toThrow(/JDK/);
})
复制代码

完整的匹配器列表, 请查阅 参考文档bash

2. 测试异步代码

1. done参数 回调

使用单个参数 done 函数,Jest会等 done() 回调函数执行结束后结束测试。若是done永远不会调用,这个测试将失败。

test('the data is peanut butter', done => {
    function callback (data) {
        expect(data).toBe('peanut butter');
        done();
    }
    // fetchData 是待测试的异步函数
    fetchData(callback);
})
复制代码

2. Promise

test 返回一个Promise, Jest 会等到Promise完成调用resolve方法后结束,若是rejected, 测试自动失败。

test('the data is peanut butter', () => {
    return fetchData().then(data => {
        expect(data).toBe('peanut butter');
    })
})
复制代码

必定不要忘记把 promise 做为返回值。若是你忘了 return语句的话,在 fetchData 返回的这个 promiseresolvethen() 有机会执行以前,测试就已经被视为已经完成了。

3. Async/Await

test('the data is peanut butter', async () => {
    const data = await fetchData();
    expect(data).toBe('peanut butter');
})
复制代码
test('the fetch fails with an error', async () => {
  expect.assertions(1);
  try {
    await fetchData();
  } catch (e) {
    expect(e).toMatch('error');
  }
});
复制代码

3. setup and teardown

Jest提供辅助函数beforeEach, beforeAfter, beforeAll, beforeAfter处理运行测试前、后的一些工做。
默认状况下,beforeafter中的块能够应用到文件中的每个测试。此外,能够使用describe块将测试分组。describe块内的beforeafter只适用于该describe块内部。文件顶部的before after先执行,describe块内的before after后执行。

// 一次性设置,只须要在文件的开头作一次设置。
beforeAll(() => {
    initDatabase();
})

afterAll(() => {
    clearDatabase();
})

beforeEach(() => {
    initData(); // 每一个测试以前调用
})

afterEach(() => {
    clearData(); // 每一个测试后调用
})

test('do test1', () => {
    expect(...).toBe(...)
})

test('do test2', () => {
    expect(...).toBe(...)
})

describe('some tests', () => {
    beforeEach(() => {
        initSomeData();
    })
    
    test('test in describe', () => {
        ...
    })
})

复制代码

4. test.only

但测试失败时,第一件要检查的事就是,当仅运行这一条测试时,是否仍然失败。方法就是把test改为test.only

test.only('this will be the only test that runs', () => {
  expect(true).toBe(false);
});

test('this test will not run', () => {
  expect('A').toBe('A');
});
复制代码

5. mock函数

jest.fn

.mock 属性

全部的mock函数都有一个特殊的 .mock 属性,它保存了关于此函数如何被调用、调用时的返回值信息。 .mock属性还追踪每次调用时this的值.mock.instances

const mockFn = jest.fn()

mockFn.mock.calls.length mock方法调用的次数

mockFn.mock.calls[i][j] 第i次调用时的第j个参数

mockFn.mock.results[i] 第i次调用时的返回值

mockFn.mock.instances[i] 第i次调用时的this

mock 返回值

mock方法也能够用来在测试代码中注入测试值。

  • mockFn.mockReturnValueOnce()
  • mockFn.mockReturnVaule()
const filterTestFn = jest.fn();

// Make the mock return `true` for the first call,
// and `false` for the second call
filterTestFn.mockReturnValueOnce(true).mockReturnValueOnce(false);

const result = [11, 12].filter(filterTestFn);

console.log(result);
// > [11]
console.log(filterTestFn.mock.calls);
复制代码

mock Promise返回值

jest.mock(...) mockResolveValue

import axios from 'axios';

class Users {
    static all(){
        return axios.get('/user.json').then(resp => resp.data)
    }
}

export default Users;
复制代码

测试代码以下:

import axios from 'axios';
import Users from './users';

jest.mock('axios');

test('should fetch users', () => {
    const users = [{name: 'Blob'}]
    const resp = {data: users};
    axios.get.mockResolvedValue(resp);
    return Users.all().then(data => expect(data).toEqual(users));
})
复制代码

mock 方法的实现

  • mockImplementation
  • mockImplementationOnce
  • mockReturnThis 链式方法
const myObj = {
  myMethod: jest.fn().mockReturnThis(),
};

// is the same as
const otherObj = {
  myMethod: jest.fn(function() {
    return this;
  }),
};
复制代码

6. Snapshot Testing 快照测试

快照测试是测试你的渲染组件的图片,并将其与组件的之前的图片进行比较。

相关文章
相关标签/搜索