最近博主工作是和另一枚后端合作,但是经常发现他写的接口出错,苦逼连连。感觉不能这样下去就学写一下单元测试,等他更新代码我都跑一遍确认一下,这样工作安心多了。
经过博主一番查找,貌似被推荐比较多的有mocha
和chai
,下面记录简单使用的笔记,其他不懂的google吧!:)
由于测试的项目是前端项目,测试的方式也是打开页面。下面先说明一下目录结构
test/ vendor/ chai-as-promised.js //后面介绍是怎么使用 chai.js mocha.css mocha.js units/ account.js sample.js ... index.html index.js
测试用的页面
###index.html###Testing ###index.js###mocha.setup('tdd'); //设置使用什么模式 tdd / bdd require('units/sample')(); //引入对应测试用例mocha.run(); //运行
具体用例,关于chai的使用请看
###units/sample.js###module.exports = function(){ //chai.assert 是经典的断言风格 var assert = require('../vendor/chai').assert; //定义一组测试用例。 suite('Array', function(){ //此方法会在这个suite所有测试用例执行前执行一次,只一次,这是跟setup的区别。 suiteSetup(function(){ console.log('suitSetup...'); }); //此方法会在每个测试用例执行前都执行一遍。 setup(function(){ console.log('setup...'); }); suite('indexOf()', function(){ //具体执行的测试用例实现代码。 test('should return -1 when not present', function(){ assert.equal(-1, [1, 2, 3].indexOf(4)); }); }); suite('indexOf2()', function(){ test('should return not -1 when present', function(){ assert.equal(0, [1, 2, 3].indexOf(1)); }); }); //此方法会在每个测试用例执行后都执行一遍,与setup相反。 teardown(function(){ console.log('teardown...'); }); //此方法会在这个suite所有测试用例执行后执行一次,与suiteSetup相反。 suiteTeardown(function(){ console.log('suiteTeardown...'); }); });}
断言Promise
###units/account.js###var chai = require("../vendor/chai"), chaiAsPromised = require("../vendor/chai-as-promised");chai.use(chaiAsPromised);module.exports = function(){ //这个是项目的model类 var account = require('models/account.model') suite('Account', function(){ //测试登录 test('signin', function(){ var user = { username: "admin@ggg.com", password: "654321" } //当请求登录接口没返回用户id时显示`登录失败` return assert.eventually.deepProperty(account.signin(user), 'attrs.id', '登录失败'); }); //测试登出 test('signout', function(){ //当请求登出接口后返回对象的code属性不等于0时提示`退出失败` return assert.eventually.propertyVal(account.signout(), 'code', 0, '退出失败'); }); });}
目前会在整个项目的根目录下创建test目录进行存放测试相关的代码,使用也很方便,打开test/index.html
即可。