- Forward


ECMAScript/JavaScript Unit Testing
Using QUnit


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu

Print

Getting Started
Back SMYC Forward
  • Distribution:
    • QUnit is distributed as two files, one containing the necessary ECMAScript/JavaScript code and the other containing the necessary stylesheet
  • Setting Up:
    • Copy the two files into a folder/directory that is accessible from your project
The HTML Document
Back SMYC Forward
  • Purpose:
    • Loads the QUnit stylesheet
    • Loads the QUnit framework
    • Loads your code to be tested
    • Loads your tests
  • Use:
    • The tests are run when the HTML document is loaded
    • The document then displays the results
Tests
Back SMYC Forward
  • Encapsulation:
    • A test consists of a description and a function
    • The function contains one or more assertions, each of which corresponds to a test case
  • Some Assertions in QUnit:
    • equal(actual,expected [, message])
    • deepEqual(actual,expected [, message])
    • throws()
Tests (cont.)
Back SMYC Forward
  • A Problem:
    • Floating point arithmetic is not exact which causes problems when using == or ===
  • Solutions:
    • Write an approxEquals() function that returns a boolean and use the ok() assertion
    • Use the toFixed() method
An Example Test
Back SMYC Forward

Testing a BMI Calculator

test("Underweight Test", function() { equal(calculateBMI(123, 69).toFixed(1), 18.2); });
A Complete Example
Back SMYC Forward

Testing the BMI Calculator Click here for a demonstration.

ecmascriptexamples/clientsidebasics/bmi.js
 
ecmascriptexamples/unittesting/bmi-test.html
 
ecmascriptexamples/unittesting/bmi-test.js
 
A Warning
Back SMYC Forward
  • A Reminder:
    • The code being tested might change state information in unknown/unexpected ways (i.e., have side effects)
  • The Problem:
    • One test case can cause a side effect that leads to a failure of a later test case
  • Toward a Solution:
    • Use atomic tests (i.e., only have one test case per test)
    • Use module() to group tests
An Example that uses module()
Back SMYC Forward
ecmascriptexamples/unittesting/bmi-test-modules.js
 
An Additional Benefit of Using module()
Back SMYC Forward
  • An Observation:
    • Sometimes you want to execute the same code before and after each test case
  • Using module():
    • The module() function has an optional parameter that can be used to pass a setup and teardown function
There's Always More to Learn
Back -