前端单元测试探索

虽然很多公司有自己的测试部门,而且前端开发大多不涉及测试环节,但鉴于目前前端领域的快速发展,其涉及面越来越广,前端开发者们必然不能止步于目前的状态。我觉得学会编写良好的测试,不仅仅有利于自己整理需求、检查代码,更是一个优秀开发者的体现。

在民和等地区,都构建了全面的区域性战略布局,加强发展的系统性、市场前瞻性、产品创新能力,以专注、极致的服务理念,为客户提供成都网站制作、做网站 网站设计制作按需求定制设计,公司网站建设,企业网站建设,成都品牌网站建设,成都全网营销,成都外贸网站建设,民和网站建设费用合理。

首先不得不推荐两篇文章:

  1. 前端自动化测试探索
  2. 测试驱动开发(TDD)介绍中的误区

Intro

单元测试到底是什么?

需要访问数据库的测试不是单元测试

需要访问网络的测试不是单元测试

需要访问文件系统的测试不是单元测试

--- 修改代码的艺术

我们在单元测试中应该避免什么?

  • 太多的条件逻辑
  • 构造函数中做了太多事情
  • too many全局变量
  • too many静态方法
  • 无关逻辑
  • 过多外部依赖

TDD(Test-driven development)

测试驱动开发(TDD),其基本思路是通过测试来推动整个开发的进行。

  • 单元测试的首要目的不是为了能够编写出大覆盖率的全部通过的测试代码,而是需要从使用者(调用者)的角度出发,尝试函数逻辑的各种可能性,进而辅助性增强代码质量
  • 测试是手段而不是目的。测试的主要目的不是证明代码正确,而是帮助发现错误,包括低级的错误
  • 测试要快。快速运行、快速编写
  • 测试代码保持简洁
  • 不会忽略失败的测试。一旦团队开始接受1个测试的构建失败,那么他们渐渐地适应2、3、4或者更多的失败。在这种情况下,测试集就不再起作用

IMPORTANT

  • 一定不能误解了TDD的核心目的!
  • 测试不是为了覆盖率和正确率
  • 而是作为实例,告诉开发人员要编写什么代码
  • 红灯(代码还不完善,测试挂)-> 绿灯(编写代码,测试通过)-> 重构(优化代码并保证测试通过)

大致过程

  1. 需求分析,思考实现。考虑如何“使用”产品代码,是一个实例方法还是一个类方法,是从构造函数传参还是从方法调用传参,方法的命名,返回值等。这时其实就是在做设计,而且设计以代码来体现。此时测试为红
  2. 实现代码让测试为绿
  3. 重构,然后重复测试
  4. 最终符合所有要求:

* 每个概念都被清晰的表达

* Not Repeat Self

* 没有多余的东西

* 通过测试

BDD(Behavior-driven development)

行为驱动开发(BDD),重点是通过与利益相关者的讨论,取得对预期的软件行为的清醒认识,其重点在于沟通

大致过程

  • 从业务的角度定义具体的,以及可衡量的目标
  • 找到一种可以达到设定目标的、对业务最重要的那些功能的方法
  • 然后像故事一样描述出一个个具体可执行的行为。其描述方法基于一些通用词汇,这些词汇具有准确无误的表达能力和一致的含义。例如,expect, should, assert
  • 寻找合适语言及方法,对行为进行实现
  • 测试人员检验产品运行结果是否符合预期行为。最大程度的交付出符合用户期望的产品,避免表达不一致带来的问题

测试的分类 & 测试工具

分类

  • API/Func UnitTest

* 测试不常变化的函数逻辑

* 测试前后端API接口

  • UI UnitTest

* 页面自动截图

* 页面DOM元素检查

* 跑通交互流程

工具

  • Mocha + Chai
  • PhantomJS or CasperJS or Nightwatch.js
  • selenium

* with python

* with js

mocha + chai的API/Func UnitTest

mocha是一套前端测试工具,我们可以拿它和其他测试工具搭配。

而chai则是BDD/TDD测试断言库,提供诸如expect这样的测试语法

initial

下面两篇文章值得一看:

  1. Testing in ES6 with Mocha and Babel 6
  2. Using Babel

setup 

 
 
  1. $ npm i mocha --save-dev 
  2. $ npm i chai --save-dev  

Use with es6

babel 6+ 

 
 
  1. $ npm install --save-dev babel-register 
  2. $ npm install babel-preset-es2015 --save-dev  
 
 
  1. // package.json 
  2.   "scripts": { 
  3.     "test": "./node_modules/mocha/bin/mocha --compilers js:babel-register" 
  4.   }, 
  5.   "babel": { 
  6.     "presets": [ 
  7.       "es2015" 
  8.     ] 
  9.   } 
  10. }  

babel 5+ 

 
 
  1. $ npm install --save-dev babel-core  
 
 
  1. // package.json 
  2.   "scripts": { 
  3.     "test": "./node_modules/mocha/bin/mocha --compilers js:babel-core/register" 
  4.   } 
  5. }  

Use with coffeescript 

 
 
  1. $ npm install --save coffee-script  
 
 
  1.   "scripts": { 
  2.     "test": "./node_modules/mocha/bin/mocha --compilers coffee:coffee-script/register" 
  3.   } 
  4. }  

Use with es6+coffeescript

After done both... 

 
 
  1.   "scripts": { 
  2.     "test": "./node_modules/mocha/bin/mocha --compilers js:babel-core/register,coffee:coffee-script/register" 
  3.   } 
  4. }  
 
 
  1. # $ mocha 
  2. $ npm t 
  3. $ npm test  

chai 

 
 
  1. import chai from 'chai'; 
  2.  
  3. const assert = chai.assert; 
  4. const expect = chai.expect; 
  5. const should = chai.should();  
 
 
  1. foo.should.be.a('string'); 
  2. foo.should.equal('bar'); 
  3. list.should.have.length(3); 
  4. obj.should.have.property('name'); 
  5.  
  6. expect(foo).to.be.a('string'); 
  7. expect(foo).to.equal('bar'); 
  8. expect(list).to.have.length(3); 
  9. expect(obj).to.have.property('flavors'); 
  10.  
  11. assert.typeOf(foo, 'string'); 
  12. assert.equal(foo, 'bar'); 
  13. assert.lengthOf(list, 3); 
  14. assert.property(obj, 'flavors');  

Test

测试的一个基本思路是,自身从函数的调用者出发,对函数进行各种情况的调用,查看其容错程度、返回结果是否符合预期。 

 
 
  1. import chai from 'chai'; 
  2. const assert = chai.assert; 
  3. const expect = chai.expect; 
  4. const should = chai.should(); 
  5.  
  6. describe('describe a test', () => { 
  7.  
  8.   it('should return true', () => { 
  9.       let example = true; 
  10.       // expect 
  11.       expect(example).not.to.equal(false); 
  12.       expect(example).to.equal(true); 
  13.       // should 
  14.       example.should.equal(true); 
  15.       example.should.be.a(boolen); 
  16.       [1, 2].should.have.length(2); 
  17.   }); 
  18.    
  19.   it('should check an object', () => { 
  20.     // 对于多层嵌套的Object而言.. 
  21.     let nestedObj = { 
  22.         a: { 
  23.           b: 1 
  24.       } 
  25.     }; 
  26.     let nestedObjCopy = Object.assign({}, nestedObj); 
  27.     nestedObj.a.b = 2; 
  28.      
  29.     // do a function to change nestedObjCopy.a.b  
  30.     expect(nestedObjCopy).to.deep.equal(nestedObj); 
  31.     expect(nestedObjCopy).to.have.property('a'); 
  32.   }); 
  33. });  

AsynTest

Testing Asynchronous Code with MochaJS and ES7 async/await

mocha无法自动监听异步方法的完成,需要我们在完成之后手动调用done()方法

而如果要在回调之后使用异步测试语句,则需要使用try/catch进行捕获。成功则done(),失败则done(error) 

 
 
  1. // 普通的测试方法 
  2. it("should work", () =>{ 
  3.   console.log("Synchronous test"); 
  4. }); 
  5. // 异步的测试方法 
  6. it("should work", (done) =>{ 
  7.   setTimeout(() => { 
  8.     try { 
  9.         expect(1).not.to.equal(0); 
  10.         done(); // 成功 
  11.     } catch (err) { 
  12.         done(err); // 失败 
  13.     } 
  14.   }, 200); 
  15. });  

异步测试有两种方法完结:done或者返回Promise。而通过返回Promise,则不再需要编写笨重的try/catch语句 

 
 
  1. it("Using a Promise that resolves successfully with wrong expectation!", function() { 
  2.     var testPromise = new Promise(function(resolve, reject) { 
  3.         setTimeout(function() { 
  4.             resolve("Hello World!"); 
  5.         }, 200); 
  6.     }); 
  7.  
  8.     return testPromise.then(function(result){ 
  9.         expect(result).to.equal("Hello!"); 
  10.     }); 
  11. });  

mock

mock是一个接口模拟库,我们可以通过它来模拟代码中的一些异步操作

React单元测试

Test React Component

React组件无法直接通过上述方法进行测试,需要安装enzyme依赖。 

 
 
  1. $ npm i --save-dev enzyme 
  2. $ npm i --save-dev react-addons-test-utils  

假设有这样一个组件: 

 
 
  1. // ...省略部分import代码 
  2. class TestComponent extends React.Component { 
  3.   constructor(props) { 
  4.     super(props); 
  5.     let {num} = props; 
  6.     this.state = { 
  7.       clickNum: num 
  8.     } 
  9.     this.handleClick = this.handleClick.bind(this) 
  10.   } 
  11.  
  12.   handleClick() { 
  13.     let {clickNum} = this.state; 
  14.     this.setState({ 
  15.       clickNum: clickNum + 1 
  16.     }); 
  17.   } 
  18.  
  19.   render() { 
  20.     let {clickNum} = this.state; 
  21.     return ( 
  22.        
  23.         {clickNum} 
  24.         点我加1 
  25.       
 
  •     ) 
  •   } 
  • }  
  • 使用样例: 

     
     
    1. import React from 'react'; 
    2. import {expect} from 'chai'; 
    3. import {shallow} from 'enzyme'; 
    4.  
    5. import TestComponent from '../components/TestComponent'; 
    6.  
    7. describe('Test TestComponent', () => { 
    8.   // 创建一个虚拟的组件 
    9.   const wrapper = shallow( 
    10.       
    11.   ); 
    12.  
    13.   /*  
    14.   * 之后,我们可以: 
    15.   * 通过wrapper.state()拿到组件的state 
    16.   * 通过wrapper.instance()拿到组件实例,以此调用组件内的方法 
    17.   * 通过wrapper.find()找到组件内的子组件 
    18.   * 但是,无法通过wrapper.props()拿到组件的props 
    19.   */ 
    20.  
    21.   // 测试该组件组外层的class 
    22.   it('should render with currect wrapper', () => { 
    23.     expect(wrapper.is('.test_component')).to.equal(true); 
    24.   }); 
    25.  
    26.   // 测试该组件初始化的state 
    27.   it('should render with currect state', () => { 
    28.     expect(wrapper.state()).to.deep.equal({ 
    29.       clickNum: 10 
    30.     }); 
    31.   }); 
    32.  
    33.   // 测试组件的方法 
    34.   it('should add one', () => { 
    35.     wrapper.instance().handleClick(); 
    36.     expect(wrapper.state()).to.deep.equal({ 
    37.       clickNum: 11 
    38.     }); 
    39.   }); 
    40. });  

    Test Redux

    redux身为纯函数,非常便于mocha进行测试 

     
     
    1. // 测试actions 
    2. import * as ACTIONS from '../redux/actions'; 
    3.  
    4. describe('test actions', () => { 
    5.   it('should return an action to create a todo', () => { 
    6.     let expectedAction = { 
    7.         type: ACTIONS.NEW_TODO, 
    8.         todo: 'this is a new todo' 
    9.     }; 
    10.      expect(ACTIONS.addNewTodo('this is a new todo')).to.deep.equal(expectedAction); 
    11.   }); 
    12. });  
     
     
    1. // 测试reducer 
    2. import * as REDUCERS from '../redux/reducers'; 
    3. import * as ACTIONS from '../redux/actions'; 
    4.  
    5. describe('todos', () => { 
    6.   let todos = []; 
    7.   it('should add a new todo', () => { 
    8.       todos.push({ 
    9.         todo: 'new todo', 
    10.         complete: false 
    11.     }); 
    12.     expect(REDUCERS.todos(todos, { 
    13.         type: ACTIONS.NEW_TODO, 
    14.         todo: 'new todo' 
    15.     })).to.deep.equal([ 
    16.       { 
    17.           todo: 'new todo', 
    18.           complete: false 
    19.       } 
    20.     ]); 
    21.   }); 
    22. });  
     
     
    1. // 还可以和store混用 
    2. import { createStore, applyMiddleware, combineReducers } from 'redux'; 
    3. import thunk from 'redux-thunk'; 
    4. import chai from 'chai'; 
    5. import thunkMiddleware from 'redux-thunk'; 
    6. import * as REDUCERS from '../redux/reducers'; 
    7. import defaultState from '../redux/ConstValues'; 
    8. import * as ACTIONS from '../redux/actions' 
    9.  
    10. const appReducers = combineReducers(REDUCERS); 
    11. const AppStore = createStore(appReducers, defaultState, applyMiddleware(thunk)); 
    12. let state = Object.assign({}, AppStore.getState()); 
    13.  
    14. // 一旦注册就会时刻监听state变化 
    15. const subscribeListener = (result, done) => { 
    16.   return AppStore.subscribe(() => { 
    17.     expect(AppStore.getState()).to.deep.equal(result); 
    18.     done(); 
    19.   }); 
    20. }; 
    21.  
    22. describe('use store in unittest', () => { 
    23.   it('should create a todo', (done) => { 
    24.     // 首先取得我们的期望值 
    25.       state.todos.append({ 
    26.         todo: 'new todo', 
    27.         complete: false 
    28.     }); 
    29.      
    30.     // 注册state监听 
    31.     let unsubscribe = subscribeListener(state, done); 
    32.     AppStore.dispatch(ACTIONS.addNewTodo('new todo')); 
    33.     // 结束之后取消监听 
    34.     unsubscribe(); 
    35.   }); 
    36. });  

    基于phantomjs和selenium的UI UnitTest

    PhantomJS是一个基于webkit的服务器端JavaScript API,即相当于在内存中跑了个无界面的webkit内核的浏览器。通过它我们可以模拟页面加载,并获取到页面上的DOM元素,进行一系列的操作,以此来模拟UI测试。但缺点是无法实时看见页面上的情况(不过可以截图)。

    而Selenium是专门为Web应用程序编写的一个验收测试工具,它直接运行在浏览器中。Selenium测试通常会调起一个可见的界面,但也可以通过设置,让它以PhantomJS的形式进行无界面的测试。

    Getting started with Selenium Webdriver for node.js

    分享名称:前端单元测试探索
    本文网址:http://www.hantingmc.com/qtweb/news48/269098.html

    网站建设、网络推广公司-创新互联,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等

    广告

    声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联

    猜你还喜欢下面的内容

    做网站知识

    分类信息网站