前端单元测试框架jest总结

1、jest--环境搭建:
安装VSCode (VSCodeUserSetup-x64-1.40.2.exe)
安装node.js (node-v16.13.1-x64.msi)(下载地址:https://nodejs.org/en/download/)
安装完成后cmd输入
node -v
npm -v

查看是否安装成功

cmd进入\Front-end Testing Demo\example目录下输入命令:npm install安装所需要的依赖包 (只有第一次需要安装依赖包)
安装完成后,输入npm test运行用例
选择a运行所有的用例 输入p是选择运行哪个文件的用例

2、jest--架构:(react+jest框架)

   2.1.项目入口:src/index.js文件,在这里导入需要执行的文件
需要执行的文件CheckboxWithLabel.js在App目录下
src/index.js
import {CheckboxWithLabels} from '
./App/index';

(import时默认的方法名不需要加{},不是默认的方法名需要加{})
ReactDOM.render(
<React.StrictMode>
<CheckboxWithLabels />
</React.StrictMode>,
document.getElementById('root')
);
2.2.在需要执行的文件所在的项目目录下的index.js文件中,引入这个文件,才能运行这个文件
App/index.js
import CheckboxWithLabel from "./CheckboxWithLabel";
export function CheckboxWithLabels() {
return (
<>
<CheckboxWithLabel />
</>
);
}
在cmd窗口Front-end Testing Demo\example目录下输入npm start就可以预览文件
2.3.在src/_test_目录下创建测试文件CheckboxWithLabel.test.js
命名规则:xxx.test.js或者xxx.spec.js

3.jest--用法

3.1.匹配器:

判断数组:toBe 、 toEqual 
expect(2 + 2).toBe(4);
expect(data).toEqual({one: 1, two: 2});
判断浮点数:toBeCloseTo
expect(value).toBeCloseTo(0.3); 
判断异常:toThrow
expect(compileAndroidCode).toThrow(ConfigError);

3.2.异步测试:回调函数、Promise 、async函数

回调函数示例:
<body>
    <button onclick="test(callback)">测试</button>
</body>

<script>
function test(a){
    const val =  doFirst()
    console.log(3)
    a && a(val)
}
function doFirst(){
    console.log(1)
    console.log(2)
    return 'HELLO'
}
function callback(value){
    console.log('我最后执行的',value)
}
</script>

Promise示例:.resolves / .rejects匹配器
test('the data is peanut butter', () => {
  return fetchData().then(data => {
    expect(data).toBe('peanut butter');
  });
});
test('the data is peanut butter', () => {
  return expect(fetchData()).resolves.toBe('peanut butter');
});
test('the fetch fails with an error', () => {
  return expect(fetchData()).rejects.toMatch('error');
});

Async/Await示例:
test('the data is peanut butter', async () => {
  const data = await fetchData();
  expect(data).toBe('peanut butter');
});
test('the data is peanut butter', async () => {
  await expect(fetchData()).resolves.toBe('peanut butter');
});
test('the fetch fails with an error', async () => {
  await expect(fetchData()).rejects.toMatch('error');
});

3.3.测试前后逻辑处理:beforeAll/afterAll、beforeEach/afterEach

beforeAll(() => {
  console.log("this is beforeAll");
});

afterAll(() => {
  console.log("this is afterAll");
});

beforeEach(() => {
  console.log("this is beforeEach");
});

afterEach(() => {
  console.log("this is afterEach");
});

3.4.Mock函数

示例1:
test('mockCallback', () => {
  //通过jest.fn 可以得到一个 mock 函数
  const mockCallback = jest.fn(x => 42 + x);
  [0, 1].forEach(mockCallback);

  // 此 mock 函数被调用了两次
  expect(mockCallback.mock.calls.length).toBe(2);
  
  // 第一次调用函数时的第一个参数是 0
  expect(mockCallback.mock.calls[0][0]).toBe(0);

  // 第二次调用函数时的第一个参数是 1
  expect(mockCallback.mock.calls[1][0]).toBe(1);

  // 第一次函数调用的返回值是 42
  expect(mockCallback.mock.results[0].value).toBe(42);
});
示例2:
test('mockCallback', () => {
  const myMock = jest.fn();
  const a = new myMock();
  const b = {name:'b'};
  const bound = myMock.bind(b);
  bound();
  console.log(myMock.mock.instances);
  // 这个函数被实例化两次
  expect(myMock.mock.instances.length).toBe(2);
  // 这个函数被第一次实例化返回的对象中,有一个 name 属性,且被设置为了 'b' 
  expect(myMock.mock.instances[1].name).toEqual('b');
});
示例3:
users.js
import axios from 'axios';
class Users {
  static all() {
    return axios.get('/users.json').then(resp => resp.data);
  }
}
export default Users;

users.test.js
import axios from 'axios';
import Users from './users';
jest.mock('axios');
test('should fetch users', () => {
  const users = [{name: 'Bob'}];
  const resp = {data: users};
  axios.get.mockResolvedValue(resp);

  return Users.all().then(data => expect(data).toEqual(users));
});

3.5.快照测试

示例:
test('object equals', () => {
  const user = {
  createdAt: new Date(),
  id: Math.floor(Math.random() * 20),
  name: 'LeBron James',
  };

expect(user).toMatchSnapshot({
  createdAt: expect.any(Date),
  id: expect.any(Number),
  });
});
执行之后会在_test_目录下生成一个_snapshots_目录 生成一份快照
当用例中的值发生变化后,与快照不一致,用例执行会失败
比如name: 'LeBron James'改为name: 'LeBron James1'再执行用例,用例执行会失败

jest函数单元测试 相关网站:

https://jestjs.io/zh-Hans/docs/getting-started (官网)

https://www.sohu.com/a/259962384_505779

 

 
 
 
posted @ 2021-12-29 11:25  zhanchenglan  阅读(198)  评论(0编辑  收藏  举报