JS 單元測試

來源:互聯網
上載者:User

標籤:

JS單元測試,我工作時主要以mocha + chai 下面時具體的文檔:

mocha:

  https://mochajs.org/#asynchronous-code

Chai:

  http://chaijs.com/api/bdd/#method_ownproperty

還是比較簡單的所以可以自己查看文檔:

 

例子基於requirejs,並且配置需基於你自己檔案目錄,紅色代碼請留意下

要測試的一個排序函數,對對象數組進行升、降序排序

 

define([‘underscore‘], function(_) {  function util() {};    //對象數組,根據item中某欄位排序    util.sortBy = function () {    var obj = arguments[0],  key = arguments[1];    if(!_.isArray(obj) || !key) {      return obj;    }        var sort = arguments[2], j = 1, temp = {};         //交換函數       function swap (obj, index) {      temp = obj[index];      obj[index] = obj[index+1];      obj[index+1] = temp;    }    //sort 預設從小到大 (採用冒泡)    obj.forEach(function() {      for(var i = 0, length = obj.length-j; i < length; i++) {        if (sort && sort.toLowerCase() ==="desc") {  //降序          if (!obj[i][key]) {            if (obj[i+1][key]) {              swap(obj, i);                     }          } else if (obj[i+1][key] && obj[i+1][key] > obj[i][key]) {                        swap(obj, i);          }        } else { //預設升序          if (obj[i][key]) {            if (obj[i+1][key]) {              if(obj[i][key] > obj[i+1][key]){                                swap(obj, i);              }                          } else {                            swap(obj, i);            }                   }        }              }      j++;    });     return obj;       }  return util;})

測試頁面代碼,具體的配置需要根據你自己的環境去配置

<!DOCTYPE html><html>    <head>        <title>H5 test</title>        <link rel="stylesheet" type="text/css" href="../../node_modules/mocha/mocha.css">        <script src="../asset/src/h5/vendor/require.js">            </script>    </head>    <body>        <div id="mocha"></div>    </body>    <script type="text/javascript">             (function(){            function nodePath(path) {                                return ‘../../node_modules/‘ + path + ‘/‘ + path;            };            function modulePath(path) {                return ‘./lib/‘ + path;            };             function vendorPath(path) {                 return ‘../asset/src/h5/vendor/‘ +path;             };            function widgetPath(path) {                return ‘../asset/src/widget/‘ + path;            };            requirejs.config({                urlArgs: Date.now(),                baseUrl: ‘./‘,                shim: {                    mocha: {                exports: ‘mocha‘              }                 },                paths: {                    ‘underscore‘: vendorPath(‘underscore‘),                    ‘mocha‘: nodePath(‘mocha‘),                    ‘chai‘: nodePath(‘chai‘),                    ‘testUtil‘: modulePath(‘testUtil‘),                     ‘util‘: widgetPath(‘util‘)                }            });                        requirejs([‘mocha‘, ‘chai‘], function(mocha, chai) {                                mocha.setup(‘bdd‘);                window.expect = chai.expect;                //載入測試模組                require([‘testUtil‘], function() {                        if(window.mochaPhantomJS) {                        window.mochaPhantomJS.run();                    } else {                        mocha.run();                    }                })            });        })();    </script></html>

 具體的測試代碼:

describe(‘util‘, function(util) {  var util;  before(function(done){    require([‘util‘], function(one) {      util = one;        done();    });  })  describe(‘#sortBy‘, function() {    it(‘obj類型數組asc排序‘, function() {      //expect(util.sortBy([{a:1, b: 1}, {a:4, b:5}, {a:3}, {a:2}, {b:2}, {a:5}], ‘a‘) == [{b:2}, {a:1, b:1}, {a:2}, {a:3}, {a:4, b:5}, {a:5}]).to.be.true;;      var str=‘‘;      util.sortBy([{a:1, b: 1}, {a:4, b:5}, {a:3}, {a:2}, {b:2}, {a:5}], ‘a‘).forEach(function(item) {        str = str + item.a +",";      })      expect(str === "undefined,1,2,3,4,5,").to.be.true;    })    it(‘obj類型數組desc排序‘, function() {      var str=‘‘;      util.sortBy([{a:1, b: 1}, {a:4, b:5}, {a:3}, {a:2}, {b:2}, {a:5}], ‘a‘, ‘desc‘).forEach(function(item) {        str = str + item.a +",";      })            expect(str ==="5,4,3,2,1,undefined,").to.true;    });    it(‘ddd‘, function() {      expect(1==2).to.true;    })  });});

 

 運行結果圖

 

 

JS 單元測試

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.