前端自动化测试 —— TDD环境配置(React+TypeScript)

欢迎讨论与指导:)

  前言

    TDD —— Test-Drive Development是测试驱动开发的意思,是敏捷开发中的一项核心实践和技术,也是一种测试方法论。TDD的原理是在开发功能代码之前,先编写单元测试用例代码,测试代码确定需要编写什么产品代码 —— 引自百度百科。

    在开发时,希望能够改动项目代码或者测试代码时能够自动进行测试,并停止上一次的测试(如果有的话)。因此基本测试架构为gulp+mocha+enzyme:gulp进行文件监听,mocha为测试框架,enzyme是针对react组件测试的一个库。配合IDE,能够实现开发的同时进行测试,并能立即观察到测试结果。

    本文不足:只描述出开发时的测试,对集成测试、跨浏览器测试还没有涉足。笔者努力中 O(∩_∩)O

    更详尽的代码在demo git地址:https://github.com/Penggggg/tdd-demo

  预览图

   gulp监听

var gulp = require('gulp');
const child_process = require('child_process');
var workerProcess;

gulp.task('default',['run_test'] ,function(){
    console.log('run default')
})

gulp.task('run_test', function(){
    gulp.watch(['src/**','test/**']) // 自定义监听文件,一个是项目代码,一个是测试代码
        .on('change', function( ){
            runTest( );
        })
    runTest( );
})

function runTest( ) {
   // 杀掉上一次测试 
    try{ if( workerProcess!==undefined || workerProcess!==null ) {workerProcess.kill( );} }catch(e) {  }
    // 重启测试
    workerProcess = child_process.exec( 
        'mocha --compilers ts:ts-node/register ./test/**/*.test.tsx --require ./config/dom.env.js', function( error, stdout, stderr ) {
         if ( error ) { console.log( error.stack )}
         console.log( stdout );
         console.log( stderr )
    })
}

   mocha环境配置

    由于是和Typescript进行配合,测试代码需要进行ts的编译,因此需要下载 ts-node 和测试框架 mocha (上文的倒数第6行代码)。

   enzyme环境配置

     小坑 1:测试文件后缀要写为 .tsx 而不是 .ts ,否则组件的尖括号无法被解析 let c = shallow(<Counter />); 

     小坑 2 :需要预先配置好dom环境并在启动mocha时首先加载  'mocha --compilers ts:ts-node/register ./test/**/*.test.tsx --require ./config/dom.env.js' 

// dom.env.js

var jsdom = require('jsdom');

if (typeof document === 'undefined') {
  global.document = jsdom.jsdom('<!doctype html><html><body></body></html>');
  global.window = document.defaultView;
  global.navigator = global.window.navigator;
}

  IDE配合

    如果想一边编码一边能看到测试效果就需要IDE配合了(如上图),而不是另外开一个cmd。

    这里推荐VSCode(F1搜索terminal并打开)和Atom(安装atom-terminal插件)

    

    

原文地址:https://www.cnblogs.com/BestMePeng/p/react_ts_tdd.html