若有排版乱掉,参阅https://www.zybuluo.com/bornkiller/note/30734。
前端测试框架推荐karma,断言库推荐jasmine
断言库,再配合jasmine-ajax
, jasmine-jquery
扩展,能够实现比较完整的前端测试。关于jquery的测试场景可能很少见,但有备无患。html
声明一个sample模块,emphasize进行DOM操做, getContent从后台获取数据。按照requirejs的AMD实现规范定义便可。前端
// ./modules/jquery/sample.js define(['jquery'], function($) { var sample = {}; sample.emphasize = function() { $('h3:first').addClass('title-emphasize'); $('p:first').addClass('content-emphasize'); }; sample.getContent = function() { $.getJSON('/api/content') .done(function(data) { $('h3:first').text(data.title); $('p:first').text(data.content); }) }; return sample; });
karma默认的index.html文件body内部为空,目的为方便测试。但进行DOM操做的模块依赖DOM才能进行,因此须要重定义view,并在测试时引入,此处定义简易。jquery
<h3 class="title">love story</h3> <p class="content">Love is complicated</p>
jasmine.getFixtures().fixturesPath
配置view加载相对路径jasmine.getFixtures().load
将view内容加载进当前页面ajax
define(['sample'], function(sample) { describe('just jquery test sample', function () { beforeEach(function () { jasmine.getFixtures().fixturesPath = '/base/views/'; jasmine.getJSONFixtures().fixturesPath = '/base/configs'; }); beforeEach(function () { jasmine.getFixtures().load('sample.html'); jasmine.Ajax.install(); }); it('just check view load', function () { expect($('h3:first')).toHaveClass('title'); expect($('p:first')).toHaveClass('content'); }); it('just check sample module emphasize', function() { sample.emphasize(); expect($('h3:first')).toHaveClass('title-emphasize'); expect($('p:first')).toHaveClass('content-emphasize'); }); it('just check data load', function() { sample.getContent(); expect(jasmine.Ajax.requests.mostRecent().url).toBe('/api/content'); jasmine.Ajax.requests.mostRecent().response({ "status": 200, "contentType": "application/json", "responseText": '{"title": "inception", "content": "youth is not a time of life"}' }); expect($('h3:first')).toContainText('inception'); expect($('p:first')).toContainText('youth is not a time of life'); }); afterEach(function () { jasmine.Ajax.uninstall(); }); }); });
一个完整的Ajax请求以下图所示。
从测试的角度来说,须要将服务器响应排除在外,不能构建数据测试桩来干涉,这破坏了单元测试的基本原则。同时,对该操做,只在意请求是否正确发出,数据返回后回调函数是否执行预期功能。因此我的感受不该该对回调函数启用spy
,而应该对最终的页面表现进行断定。本例中,测试<h3></h3>
和<p></p>
里是否包含对应内容。json
Email: 491229492@qq.comapi