14 Unit testing with QUnit

This chapter covers

  • Why testing is important
  • What unit testing means
  • Installing QUnit
  • Testing your JavaScript code with QUnit
  • How to create a complete test suite with QUnit

14.1 Why is testing important

14.1.1 Why unit testing


  • Attest that the code returns expected results given specific inputs.
  • Discover the highest number of defects in an early stage (related to the previous point).
  • Improve the design of the code.
  • Identify units that are too complex.

14.1.2 Frameworks for unit testing


JavaScript
QUnit
Mocha
Jasmine (behavior-driven development)


14.2 Getting started with QUnit

14.3 Creating tests for synchronous code


QUnit.test(name, test)
Parameters
name (String)
test (Function)
Returns
undefined

QUnit.test('My first test', function(assert) {
  //Code here...
});

expect(total)
Parameters
total (Number)
Returns
undefined

QUnit.test('My first test', function(assert){
  assert.expect(0);
});

14.4 Testing your code using assertions

14.4.1 equal(), strictEqual(), notEqual(), and notStrictEqual()


equal(value, expected[, message])
Parameters
value (Any)
expected (Any)
message (String)
Returns
undefined

function sum(a, b) {
return a + b;
}

QUnit.test('My first test', function(assert) {
 assert.expect(3);
 assert.equal(sum(2, 2), 4, 'Sum of two positive numbers');
 assert.equal(sum(-2, -2), -4, 'Sum of two negative numbers');
 assert.equal(sum(2, 0), 2, 'Sum of a positive number and the neutral
element');
});

strictEqual(value, expected[, message])
Parameters
value (Any)
expected (Any)
message (String)
Returns
undefined

assert.equal($.trim(' '), '',
 'Trimming a spaces-only string returns an empty string');
assert.strictEqual($('input:checked').length,
 $('input').filter(':checked').length,
 'Filtering elements in advance or later produce the same number of
 elements');
assert.notEqual($('input:checked'), $('input').filter(':checked'),
 'Two jQuery objects are different unless they point to the same memory
 address');
assert.notStrictEqual(new Array(1, 2, 3), [1, 2, 3],
 'Two arrays are different unless they point to the same memory address');

14.4.2 The other assertion methods


An overview of other assertion methods provided by QUnit

Method Description
deepEqual(value, expected[, message])
notDeepEqual(value, expected[, message])
propEqual(value, expected[, message])
notPropEqual(value, expected[, message])
ok(value[, message])
function isEven(number) {
  return number % 2 === 0;
}

assert.strictEqual(isEven(4), true, '4 is an even number');
assert.ok(isEven(4), '4 is an even number');

14.4.3 The throws() assertion method


throws(function[, expected][, message])
Parameters
function (Function)
expected (Object|Function|RegExp)
message (String)
Returns
undefined

function isEven(number) {
 if (typeof number !== 'number') {
 throw new Error('The passed argument is not a number');
 }
 return number % 2 === 0;
}

assert.throws(
 function() {
 isEven('test');
 },
 new Error('The passed argument is not a number'),
 'Passing a string throws an error'
);

14.5 How to test asynchronous tasks


async
Parameters
none
Returns
A unique resolution callback function.

QUnit.test('Testing asynchronous code', function(assert) {
 var $fixtures = $('#qunit-fixture');
 assert.expect(4);
 assert.strictEqual(
 $fixtures.children().length,
 0,
 'The children of qunit-fixtures are 0'
 );
 var firstCallback = assert.async();
 window.setTimeout(function() {
 assert.ok(isEven(4), '4 is even');
 firstCallback();
 }, 500);
 var secondCallback = assert.async();
 $fixtures.load('test.1.html #qunit', function() {
 assert.ok(
 true,
 'File test.1.html has been successfully loaded'
 );
 assert.strictEqual(
 $fixtures.children().length,
 1,
 'The elements appended to qunit-fixtures are 1'
);
 secondCallback();
 });
 });

14.6 noglobals and notrycatch


QUnit.test('Testing the noglobals option', function(assert) {
 assert.expect(1);
 window.bookName = 'jQuery in Action';
 assert.strictEqual(bookName, 'jQuery in Action', 'Strings are equal');
});
QUnit.test('Testing the notrycatch option', function(assert) {
 assert.expect(1);
 assert.strictEqual(add(2, 2), 4, 'The sum of 2 plus 2 is equal to 4');
});

14.7 Group your tests in modules


QUnit.module(name[, lifecycle])
Parameters
name (String)
lifecycle (Object)
Returns
undefined

QUnit.module('Core');
QUnit.test('First test', function(assert) {
 assert.expect(1);
 assert.ok(true);
});

QUnit.module('Ajax');
QUnit.test('Second test', function(assert) {
 assert.expect(1);
 assert.ok(true);
});

14.8 Configuring QUnit


The configuration properties of QUnit.config

Name Description
altertitle
autostart
hidepassed
moduleFilter
reorder
requireExpects
testId
testTimeout
scrolltop
urlConfig
QUnit.config.hidepassed = true;

QUnit.config.requireExpects = true;

14.9 An example test suite

14.10 Summary

最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末搭综,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子损趋,更是在濱河造成了極大的恐慌术幔,老刑警劉巖,帶你破解...
    沈念sama閱讀 216,544評論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件梯影,死亡現(xiàn)場離奇詭異巫员,居然都是意外死亡,警方通過查閱死者的電腦和手機甲棍,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,430評論 3 392
  • 文/潘曉璐 我一進店門简识,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人感猛,你說我怎么就攤上這事七扰。” “怎么了陪白?”我有些...
    開封第一講書人閱讀 162,764評論 0 353
  • 文/不壞的土叔 我叫張陵颈走,是天一觀的道長。 經(jīng)常有香客問我咱士,道長立由,這世上最難降的妖魔是什么轧钓? 我笑而不...
    開封第一講書人閱讀 58,193評論 1 292
  • 正文 為了忘掉前任,我火速辦了婚禮锐膜,結果婚禮上毕箍,老公的妹妹穿的比我還像新娘。我一直安慰自己枣耀,他們只是感情好霉晕,可當我...
    茶點故事閱讀 67,216評論 6 388
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著捞奕,像睡著了一般牺堰。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上颅围,一...
    開封第一講書人閱讀 51,182評論 1 299
  • 那天伟葫,我揣著相機與錄音,去河邊找鬼院促。 笑死筏养,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的常拓。 我是一名探鬼主播渐溶,決...
    沈念sama閱讀 40,063評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼弄抬!你這毒婦竟也來了茎辐?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 38,917評論 0 274
  • 序言:老撾萬榮一對情侶失蹤掂恕,失蹤者是張志新(化名)和其女友劉穎拖陆,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體懊亡,經(jīng)...
    沈念sama閱讀 45,329評論 1 310
  • 正文 獨居荒郊野嶺守林人離奇死亡依啰,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,543評論 2 332
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了店枣。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片速警。...
    茶點故事閱讀 39,722評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖鸯两,靈堂內(nèi)的尸體忽然破棺而出坏瞄,到底是詐尸還是另有隱情,我是刑警寧澤甩卓,帶...
    沈念sama閱讀 35,425評論 5 343
  • 正文 年R本政府宣布,位于F島的核電站蕉斜,受9級特大地震影響逾柿,放射性物質發(fā)生泄漏缀棍。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,019評論 3 326
  • 文/蒙蒙 一机错、第九天 我趴在偏房一處隱蔽的房頂上張望爬范。 院中可真熱鬧,春花似錦弱匪、人聲如沸青瀑。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,671評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽斥难。三九已至,卻和暖如春帘饶,著一層夾襖步出監(jiān)牢的瞬間哑诊,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,825評論 1 269
  • 我被黑心中介騙來泰國打工及刻, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留镀裤,地道東北人。 一個月前我還...
    沈念sama閱讀 47,729評論 2 368
  • 正文 我出身青樓缴饭,卻偏偏與公主長得像暑劝,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子颗搂,可洞房花燭夜當晚...
    茶點故事閱讀 44,614評論 2 353

推薦閱讀更多精彩內(nèi)容