jest单元测试实践总结及react单元测试

jest 是facebook推出的一款测试框架,集成了 Mocha,chai,jsdom,sinon等功能。

基本用法

和 mocha 和 chai 的功能很像,甚至可以兼容部分 mocha 和 chai 的语法。可以这么写

import React from 'react'
import { shallow } from 'enzyme'
import CommentItem from './commentItem'

describe('测试评论列表项组件', () => {
  // 这是mocha的玩法,jest可以直接兼容
  it('测试评论内容小于等于200时不出现展开收起按钮', () => {
    const propsData = {
      name: 'hj',
      content: '测试标题'
    }
    const item = shallow(<CommentItem {...propsData} />);
    // 这里的断言实际上和chai的expect是很像的
    expect(item.find('.btn-expand').length).toBe(0);
  })

  // 这是jest的玩法,推荐用这种
  test('两数相加结果为两个数字的和', () => {
    expect(3).toBe(3);
  });
}

jest安装

npm install jest -g

全局安装过后,可以使用jest命令

生成配置文件:

jest --init

执行过程中会询问一些问题,根据项目实际需要选择,之后生成jest.config.js文件

引入babel-jest

npm install  babel-jest @babel/core @babel/preset-env --dev

jest命令执行时会自动查询babel-jest模块

jest --coverage生成覆盖率报告

jest测试实例

export function isPromise(obj){
  return !!obj && (typeof obj === 'function' || typeof obj === 'object') && typeof obj.then === 'function'
}
import { isPromise } from '../../src/utils/isPromise'

describe("isPromise",() => {
  it('test Promise isPromise',() => {
    const test_promise = new Promise((resolve,reject) => {});
    expect(isPromise(test_promise)).toBe(true)
  })

  it('test object isPromise',() => {
    const not_promise = {
      then:function(){}
    }
    expect(isPromise(not_promise)).toBe(true)
  })
})

高级用法:

describe块之中,提供测试用例的四个函数:before()、after()、beforeEach()和afterEach()。它们会在指定时间执行(如果不需要可以不写)

describe('加法函数测试', () => {

  before(() => {// 在本区块的所有测试用例之前执行
  });

  after(() => {// 在本区块的所有测试用例之后执行
  });

  beforeEach(() => {// 在本区块的每个测试用例之前执行
  });

  afterEach(() => {// 在本区块的每个测试用例之后执行
  });


  it('1加1应该等于2', () => {
     expect(add(1, 1)).toBe(2);
  });
  it('2加2应该等于4', () => {
      expect(add(2, 2)).toBe(42);
  });

});

react单元测试

react提供了两个测试的库,react-test-renderer和react-dom/test-utils

react-test-renderer

实例:

import React, { Component } from 'react'

export default class Button extends Component {
  onClick = () => {
    console.log('点击事件')
  }
  render() {
    return (
      <button onClick = {this.onClick}>
        {this.props.text}
      </button>
    )
  }
}
import React from 'react'
import Button from '../../src/components/Button'
import ShallowRenderer from 'react-test-renderer/shallow'
import TestUtils from 'react-dom/test-utils'

test('Button render with text', () => {
  const text = "text";
  const renderer = new ShallowRenderer();
  renderer.render(<Button text = {text}/>);
  const button = renderer.getRenderOutput();
  expect(button.type).toBe('button');
  expect(button.props.children).toBe(text)
})

react-dom/test-utils

详细文档移步官网:https://reactjs.org/docs/test-utils.html#renderintodocument

使用之前请先将jest.config.js中的testEnvironment:设置为"jsdom"

// The test environment that will be used for testing
  testEnvironment: "jsdom",
import React from 'react'
import Button from '../../src/components/Button'
import ShallowRenderer from 'react-test-renderer/shallow'
import TestUtils from 'react-dom/test-utils'


test('Button render with text', () => {
  const text = "text";
  const renderer = new ShallowRenderer();
  renderer.render(<Button text = {text}/>);
  const button = renderer.getRenderOutput();
  expect(button.type).toBe('button');
  expect(button.props.children).toBe(text)
})



it('Button onClick test', () => {
  const onClick = jest.fn();
  //这里要设置 testEnvironment: "jsdom",否则会报错
  const tree = TestUtils.renderIntoDocument(<Button onClick = {onClick()} text="测试"/>);
  const button = TestUtils.findRenderedDOMComponentWithTag(
    tree,
    'button'
  )
  //[ˈsɪmjuleɪt] 模拟
  TestUtils.Simulate.click('button');
  expect(onClick).toBeCalled()
})

第三方测试库:enzyme

实例

/* eslint-env jest */
import { shallow } from 'enzyme';
import React from 'react';
import Page404 from '../components/Page404';

describe('Page404', () => {
  it('Page404 shows "404"', () => {
    const app = shallow(<Page404 />);
    expect(app.find('div').text()).toEqual('404');
  });
});

 

 

参考:http://loveky.github.io/2018/06/05/unit-testing-react-component-with-jest/

https://www.jianshu.com/p/eaaf07c1b88f

https://www.cnblogs.com/susu8/p/9512393.html

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值