若有排版亂掉,參閱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