看了下mbraak-simple-data-grid写的单元测试,感觉还是很好入手的

用module函数定义模块

用test函数定义测试方法

用equal、ok(判断是否为真)等方法做断言判断

用setup方法做前置条件设置

用teardown做后置条件设置

贴一下mbraak-simple-data-grid测试完的结果界面 和其测试代码,详细的可以到其主页下载整个代码包

测试页的html代码

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Simple data grid - Test</title> <link rel="stylesheet" href="../extra/bower_components/qunit/qunit/qunit.css"> <!--[if lt IE 9]>
<script src="../extra/jquery-1.11.3.min.js"></script>
<![endif]-->
<!--[if gte IE 9]><!-->
<script src="../extra/bower_components/jquery/dist/jquery.min.js"></script>
<!--<![endif]--> <script src="../extra/bower_components/jquery-mockjax/dist/jquery.mockjax.js"></script>
<script src="../extra/bower_components/qunit/qunit/qunit.js"></script>
<script src="../extra/bower_components/blanket/dist/qunit/blanket.js"></script>
<script src="../simple.datagrid.js" data-cover></script>
<script src="test.js"></script>
</head>
<body>
<div id="qunit"></div>
</body>
</html>

测试页的js代码

$(function() {

function formatValues($elements) {
var values = $elements.map(function() {
return $(this).text();
});
return values.toArray().join(';');
} function getRowValues($table) {
return formatValues(
$table.find('tbody td')
);
} function formatColumnNames($table) {
var columns = $table.simple_datagrid('getColumns');
var values = $.map(columns, function(column) {
return column.key;
});
return values.join(';');
} module('utils'); test('slugify', function() {
slugify = window.SimpleDataGrid.slugify; equal(slugify(''), '');
equal(slugify('abc'), 'abc');
equal(slugify('Abc'), 'abc');
equal(slugify('abc def'), 'abc_def');
equal(slugify('123'), '123');
equal(slugify('abc-def'), 'abc_def');
equal(slugify('abc_def'), 'abc_def');
}); module('simple-data-grid', {
setup: function(e) {
$('body').append(
'<table id="table1">'+
' <thead>'+
' <th>Name</th>'+
' <th>Latin name</th>'+
' </thead>'+
'</table>'
);
}, teardown: function() {
var $table1 = $('#table1');
$table1.simple_datagrid('destroy');
$table1.remove(); $.mockjax.clear();
}
}); test('get column data from <th> elements', function() {
var $table1 = $('#table1'); // Change the key of the first column to 'name1' by setting the 'data-key' property
var $name_th = $table1.find('th:first');
$name_th.attr('data-key', 'name1'); // init widget
$table1.simple_datagrid(); // check column data
var columns = $('#table1').simple_datagrid('getColumns');
equal(columns.length, 2);
equal(columns[0].title, 'Name');
equal(columns[0].key, 'name1'); // from data-key
equal(columns[1].title, 'Latin name');
equal(columns[1].key, 'latin_name'); // slug of 'Latin name'
}); test('get column data from options', function() {
// setup
var $table1 = $('#table1'); // 1. Init columns in javascript; this updates the existing columns
$table1.simple_datagrid({
columns: [
{
key: 'latin_name',
title: 'Latin'
}
]
}); var columns = $table1.simple_datagrid('getColumns');
equal(columns.length, 2);
equal(columns[1].key, 'latin_name');
equal(columns[1].title, 'Latin'); $table1.simple_datagrid('destroy'); // 2. Init columns in javascript; first remove thead
$table1.find('thead').remove(); $table1.simple_datagrid({
columns: [
'Column1',
{
title: 'Column2',
key: 'c2'
},
{
title: 'Column3'
}
]
}); // check column data
columns = $('#table1').simple_datagrid('getColumns');
equal(columns.length, 3);
equal(columns[0].title, 'Column1');
equal(columns[0].key, 'column1'); // slug of name
equal(columns[1].title, 'Column2');
equal(columns[1].key, 'c2'); // defined in options
equal(columns[2].key, 'column3');
equal(columns[2].title, 'Column3');
}); test('get data from array', function() {
var $table1 = $('#table1'); // 1. row is an array
$table1.simple_datagrid({
data: [
['Avocado', 'Persea americana']
]
});
equal(getRowValues($table1), 'Avocado;Persea americana'); // 2. make empty
$table1.simple_datagrid('loadData', []);
equal(getRowValues($table1), ''); // 3. row is an object
$table1.simple_datagrid(
'loadData',
[
{
name: "Bell pepper",
'latin_name': "Capsicum annuum"
},
{
name: 'Tomatillo' // no latin-name
}
]
);
equal(getRowValues($table1), 'Bell pepper;Capsicum annuum;Tomatillo;'); // 4. invalid data
$table1.simple_datagrid('loadData', '');
}); test('get data from ajax', function() {
// setup
var $table1 = $('#table1');
$table1.attr('data-url', '/api/fruits/'); $.mockjax({
url: '*',
responseText: '[["Winter melon", "Benincasa hispida"]]'
}); $table1.bind(
'datagrid.load_data', function() {
start();
equal(
getRowValues($table1),
'Winter melon;Benincasa hispida'
);
}
); // -- init table
$table1.simple_datagrid();
stop();
}); test('get data from ajax; define url in options', function() {
// setup
var $table1 = $('#table1'); $.mockjax({
url: '*',
responseText: [
["Cucumber", "Cucumis sativus"]
]
}); $table1.bind(
'datagrid.load_data', function() {
start(); equal(
getRowValues($table1),
'Cucumber;Cucumis sativus'
);
}
); // -- init table
$table1.simple_datagrid({
url: '/api/fruits/'
});
stop();
}); test('getSelectedRow', function() {
// setup
var $table1 = $('#table1');
$table1.simple_datagrid({
data: [
{
name: 'Avocado',
'latin_name': 'Persea americana',
id: 200
},
{
name: 'Bell pepper',
'latin_name': 'Capsicum annuum',
id: 201
}
]
}); // 1. no selection
equal($table1.simple_datagrid('getSelectedRow'), null); // 2. select second row
$table1.find('tbody tr:eq(1) td:first').click();
ok($('tbody tr:eq(1)').hasClass('sdg-selected'));
equal($table1.simple_datagrid('getSelectedRow').id, 201); // 2. select first row
$table1.find('tbody tr:eq(0) td:first').click();
ok($('tbody tr:eq(0)').hasClass('sdg-selected'));
ok(! $('tbody tr:eq(1)').hasClass('sdg-selected'));
equal($table1.simple_datagrid('getSelectedRow').id, 200);
}); test('header html', function() {
// setup
var $table1 = $('#table1');
$table1.simple_datagrid(); // 1. check html
equal(
formatValues($table1.find('thead th')),
'Name;Latin name'
); var keys = $table1.find('thead th').map(function() {
return $(this).data('key');
});
equal(keys.toArray().join(' '), 'name latin_name');
}); test('pagination', function() {
// todo: look for better definition of the test // setup
function getResponse(settings) {
var page = settings.data.page || 1; var total_pages = 100;
var rows_per_page = 5; var rows = [];
var index = (page - 1) * rows_per_page + 1;
for (var i=0; i<rows_per_page; i++) {
rows.push({
name: 'n' + index,
'latin_name': 'l' + index
});
index += 1;
} this.responseText = {
total_pages: total_pages,
rows: rows
};
} $.mockjax({
url: '*',
response: getResponse
}); var $table1 = $('#table1'); // -- init table
$table1.simple_datagrid({ url: '/my_data/' }); function runSteps($table, steps) {
stop(); var load_count = 0; $table1.bind(
'datagrid.load_data',
function() {
var step_function = steps[load_count];
step_function(); load_count += 1; if (load_count == steps.length) {
start();
}
}
);
} runSteps(
$table1,
[
function() {
// step 1: expect first page
equal(
formatValues($table1.find('tbody td')),
'n1;l1;n2;l2;n3;l3;n4;l4;n5;l5'
); // go to next page
$table1.find('.sdg-pagination a:last').click();
},
function() {
// step 2: expect second page
equal(
getRowValues($table1),
'n6;l6;n7;l7;n8;l8;n9;l9;n10;l10'
); // go to last page
$table1.find('.sdg-pagination a:eq(10)').click();
},
function() {
// expect last page
equal(
getRowValues($('#table1')),
'n496;l496;n497;l497;n498;l498;n499;l499;n500;l500'
);
}
]
);
}); test('sorting', function() {
function getResponse(settings) {
var page = settings.data.page || 1;
var order_by = settings.data.order_by;
var sortorder = settings.data.sortorder; var data = []; if (order_by == 'name') {
if (sortorder == 'asc') {
data = [
['Avocado', 'Persea americana'],
['Bell pepper', 'Capsicum annuum'],
['Eggplant', 'Solanum melongena']
];
}
else if (sortorder == 'desc') {
data = [
['Eggplant', 'Solanum melongena'],
['Bell pepper', 'Capsicum annuum'],
['Avocado', 'Persea americana']
];
}
}
else if (order_by == 'latin_name') {
if (sortorder == 'asc') {
data = [
['Bell pepper', 'Capsicum annuum'],
['Avocado', 'Persea americana'],
['Eggplant', 'Solanum melongena']
];
}
else if (sortorder == 'desc') {
data = [
['Eggplant', 'Solanum melongena'],
['Avocado', 'Persea americana'],
['Bell pepper', 'Capsicum annuum']
];
}
} this.responseText = data;
} var $table1 = $('#table1'); function format_first_columns() {
var values = $table1.find('tbody tr').map(
function() {
return $(this).find('td:eq(0)').text();
}
); return values.toArray().join(';');
} $.mockjax({
url: '*',
response: getResponse
}); var load_count = 0; $table1.bind(
'datagrid.load_data',
function() {
if (load_count == 0) {
equal(format_first_columns(), 'Avocado;Bell pepper;Eggplant'); // -- click on 'name' -> sort descending
$table1.find('th:eq(0) a').click();
}
else if (load_count == 1) {
equal(format_first_columns(), 'Eggplant;Bell pepper;Avocado'); // -- click on 'latin-name' -> sort ascending
$table1.find('th:eq(1) a').click();
}
else if (load_count == 2) {
equal(format_first_columns(), 'Bell pepper;Avocado;Eggplant'); // -- click on 'latin-name' -> sort descending
$table1.find('th:eq(1) a').click();
}
else if (load_count == 3) {
equal(format_first_columns(), 'Eggplant;Avocado;Bell pepper'); // -- click on 'latin-name' -> sort ascending
$table1.find('th:eq(1) a').click();
}
else {
start();
} load_count += 1;
}
); // -- init tree; order by name
$table1.simple_datagrid({
url: '/fruits/',
order_by: 'name'
});
stop();
}); test('reload', function() {
// setup
var $table1 = $('#table1');
$table1.simple_datagrid({
data: [
['Avocado', 'Persea americana']
]
}); equal(getRowValues($table1), 'Avocado;Persea americana'); // 1. empty html
$table1.find('tbody tr').detach();
equal(getRowValues($table1), ''); // 2. reload
$table1.simple_datagrid('reload');
equal(getRowValues($table1), 'Avocado;Persea americana');
}); test('setParameter', function() {
// setup
stop(); var response_count = 0; function getResponse(settings) {
var my_param = settings.data.my_param; if (response_count == 0) {
equal(my_param, undefined);
}
else if (response_count == 1) {
equal(my_param, 'abc');
} response_count += 1; this.responseText = [
['Avocado', 'Persea americana']
];
} $.mockjax({
url: '*',
response: getResponse
}); var $table1 = $('#table1'); var load_count = 0 $table1.bind(
'datagrid.load_data',
function() {
if (load_count == 0) {
// -- set parameter and reload
$table1.simple_datagrid('setParameter', 'my_param', 'abc');
$table1.simple_datagrid('reload');
}
else if (load_count == 1) {
start();
} load_count += 1;
}
); $table1.simple_datagrid({
url: '/fruits/'
});
}); test('setCurrentPage', function() {
// setup
stop(); var response_count = 0; function getResponse(settings) {
var page = settings.data.page; if (response_count == 0) {
equal(page, 1);
}
else if (response_count == 1) {
equal(page, 2);
} response_count += 1; this.responseText = [
['Avocado', 'Persea americana']
];
} $.mockjax({
url: '*',
response: getResponse
}); var $table1 = $('#table1'); var load_count = 0 $table1.bind(
'datagrid.load_data',
function() {
if (load_count == 0) {
// -- set current page and reload
$table1.simple_datagrid('setCurrentPage', 2);
$table1.simple_datagrid('reload');
}
else if (load_count == 1) {
start();
} load_count += 1;
}
); $table1.simple_datagrid({ url: '/fruits/' });
}); test('table with existing elements', function() {
// Test with a table that already has rows and a footer.
// The existing elements must be overwritten. // setup
var $table1 = $('#table1');
$table1.append('<tbody><tr><td>abc</td></tr></tbody');
$table1.append('<tfoot><tr><td>my footer</td></tfoot>'); // 1. init table
$table1.simple_datagrid({
data: [
['Avocado', 'Persea americana']
]
}); equal(getRowValues($table1), 'Avocado;Persea americana');
equal($table1.find('tfoot').children().length, 0);
}); test('table with empty head', function() {
// setup
var $table1 = $('#table1');
$table1.find('thead').remove(); // 1. init table
$table1.simple_datagrid({
columns: ['Column1'],
data: [['abc']]
}); equal(
$table1.find('thead th').text(),
'Column1'
);
}); test('on_generate', function() {
// Test the 'on_generate' option of a column
var $table1 = $('#table1');
$table1.find('thead').remove(); // 1. init table
$table1.simple_datagrid({
columns: [
{
title: 'Fruit',
on_generate: function(value, row) {
return '_' + value + '_';
}
},
{
title: 'Latin name',
on_generate: function(value, row) {
if (! value) {
return '[empty]';
}
else {
return value;
}
}
}
],
data: [
['Avocado']
]
}); equal(getRowValues($table1), '_Avocado_;[empty]'); // 2. load data; record is object
$table1.simple_datagrid(
'loadData',
[
{fruit: 'Tomato'}
]
); equal(getRowValues($table1), '_Tomato_;[empty]'); // 3. load data; record is array
$table1.simple_datagrid(
'loadData',
[
['Sweet pepper']
]
); equal(getRowValues($table1), '_Sweet pepper_;[empty]');
}); test('getPages', function() {
// setup
var $table1 = $('#table1');
$table1.simple_datagrid({
paginator: {
page_window: 2
}
}); function getPages(current_page, total_pages) {
return $table1.simple_datagrid('testGetPages', current_page, total_pages, 2);
} // 1. get pages
deepEqual(getPages(1, 1), [1]);
deepEqual(getPages(1, 2), [1, 2]);
deepEqual(getPages(1, 100), [1, 2, 3, 0, 99, 100]);
deepEqual(getPages(100, 100), [1, 2, 0, 98, 99, 100]);
deepEqual(getPages(50, 100), [1, 2, 0, 48, 49, 50, 51, 52, 0, 99, 100]);
deepEqual(getPages(5, 100), [1, 2, 3, 4, 5, 6, 7, 0, 99, 100]);
deepEqual(getPages(6, 100), [1, 2, 3, 4, 5, 6, 7, 8, 0, 99, 100]);
deepEqual(getPages(7, 100), [1, 2, 0, 5, 6, 7, 8, 9, 0, 99, 100]);
deepEqual(getPages(96, 100), [1, 2, 0, 94, 95, 96, 97, 98, 99, 100]);
deepEqual(getPages(95, 100), [1, 2, 0, 93, 94, 95, 96, 97, 98, 99, 100]);
deepEqual(getPages(94, 100), [1, 2, 0, 92, 93, 94, 95, 96, 0, 99, 100]);
}); test('addColumn', function() {
// setup
var $table1 = $('#table1');
$table1.simple_datagrid(); // check initial columns
equal(formatColumnNames($table1), 'name;latin_name'); // 1. add column at the end
$table1.simple_datagrid('addColumn', 'col end');
equal(formatColumnNames($table1), 'name;latin_name;col_end'); // 2. add column after 'name'
$table1.simple_datagrid('addColumn', 'col2', 1);
equal(formatColumnNames($table1), 'name;col2;latin_name;col_end'); // 2. add column at beginning
$table1.simple_datagrid('addColumn', 'col1', 0);
equal(formatColumnNames($table1), 'col1;name;col2;latin_name;col_end');
}); test('removeColumn', function() {
// setup
var $table1 = $('#table1');
$table1.simple_datagrid(); // -- remove column
$table1.simple_datagrid('removeColumn', 'name'); equal(formatColumnNames($table1), 'latin_name');
}); });

qunit.js初试的更多相关文章

  1. Auto.js 初试-Android开发JS利器

    GitHub地址:https://github.com/hyb1996/Auto.js 文档地址:https://hyb1996.github.io/AutoJs-Docs/#/?id=%E7%BB% ...

  2. require.js初试(with angular & optimization)

    如果你只是想找一款称手的js加载器,可以参考这篇js loader benchmarks(http://artzstudio.com/files/Boot/test/benchmarks/script ...

  3. 【JS单元测试】Qunit 和 jsCoverage使用方法

          近日在网上浏览过很多有关js单元测试相关的文档,工具,但是,针对Qunit 和 jsCoverage使用方法,缺少详细说明,对于初入前端的人来说,很难明白其中的意思,特此整理这篇文章,希望 ...

  4. Qunit 和 jsCoverage使用方法(js单元测试)

    Qunit 和 jsCoverage使用方法(js单元测试) 近日在网上浏览过很多有关js单元测试相关的文档,工具,但是,针对Qunit 和 jsCoverage使用方法,缺少详细说明,对于初入前端的 ...

  5. Cookbook of QUnit

    本篇文章是QUnit的简介,可以作为很好的入门教程.文章原址 介绍 自动化测试时软件开发过程中必不可少的一部分,而单元测试则是自动化测试的最为基本的一块,软件的每一个组件, 每一个功能单元都需要经过不 ...

  6. 使用QUnit进行自动化单元测试

    前言 前阵子由于项目需求接触了java的单元测试JUnit,就顺带着学习了前端的单元测试:Qunit. 既然跟测试有关,不妨介绍一下测试中的黑盒测试.白盒测试以及单元测试. 1.黑盒测试:所谓的黑盒, ...

  7. JavaScript测试工具比较: QUnit, Jasmine, and Mocha

    1. QUnit A JavaScript Unit Testing framework. QUnit is a powerful, easy-to-use JavaScript unit testi ...

  8. qunit学习(一)

    QUnit是一个强大的JavaScript单元测试框架,用于调试代码.该框架是由jQuery团队的成员所开发,并且是jQuery的官方测试套件.任意正规JavaScript代码QUnit都能测试. 其 ...

  9. ember.js:使用笔记8 加载测试与集成测试

    emberjs使用的测试工具为qunit.js: 加载:将runner.js添加到Index.html:大致内容: if (window.location.search.indexOf("? ...

随机推荐

  1. [ZZ] HDR the bungie way

    http://blog.csdn.net/toughbro/article/details/6755394 bufferencoding游戏float算法 bungie 06年,gamefest上的p ...

  2. Apache Spark源码走读之9 -- Spark源码编译

    欢迎转载,转载请注明出处,徽沪一郎. 概要 本来源码编译没有什么可说的,对于java项目来说,只要会点maven或ant的简单命令,依葫芦画瓢,一下子就ok了.但到了Spark上面,事情似乎不这么简单 ...

  3. GDC2016【全境封锁(Tom Clancy's The Division)】对为何对应Eye Tracked System,以及各种优点的演讲报告

    GDC2016[全境封锁(Tom Clancy's The Division)]对为何对应Eye Tracked System,以及各种优点的演讲报告 原文 4Gamer編集部:松本隆一 http:/ ...

  4. vue model双向绑定

    view <div id='demo' class="container"> <input type="text" v-model='name ...

  5. nginx安全相关设置

    Nginx默认是显示版本号,隐藏 # vim nginx.conf 在http {—}里加上server_tokens off; 如: http { ……省略 server_tokens off; h ...

  6. routing decisions based on paths, network policies, or rule-sets configured by a network administrator

    https://en.wikipedia.org/wiki/Border_Gateway_Protocol Border Gateway Protocol (BGP) is a standardize ...

  7. Windows注册表(持续更新)

    HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Zoom 下, 设置DWORD 值 ZoomDisabled  等于 1.

  8. 【转】C#高性能大容量SOCKET并发(二):SocketAsyncEventArgs封装

    http://blog.csdn.net/sqldebug_fan/article/details/17557341 1.SocketAsyncEventArgs介绍 SocketAsyncEvent ...

  9. SQL server 2008数据库的备份与还原(转)

      一.SQL数据库的备份: 1.依次打开 开始菜单 → 程序 → Microsoft SQL Server 2008 → SQL Server Management Studio → 数据库:Dsi ...

  10. ubuntu下opencv在Qt中的使用

    1. 编译安装OpenCV2.4.9  本博已有文章描述 2. 安装Qt和QtCreator 从qt-project.org 下载Qt安装文件 qt-opensource-linux-x64-5.4. ...