1. Assertions
The core of unit testing is assertion. The so-called assertions are an expectation of the program designer for the system to reach the state. JavaScript does not provide assertions, but we can design this method by ourselves.
function assert(msg, value) {if (!value) {throw new Error(msg);}assert.count++;return true;}assert.count = 0;
Here, the assert function is only used to see whether the second shard of a car is true (except for false, null, undefined, 0, "", and Nan ). If it is true, add 1 to the assertion counter; otherwise, an error is thrown.
2. Red and Green
In unit tests, "Red" and "green" are usually used to indicate "failure" and "success". The result is easier to understand because the test turns red or green. The following provides a simplified output function that uses Dom to display color messages.
function output(text, color) {var p = document.createElement("p");p.innerHTML = text;p.style.color = color;document.body.appendChild(p);}
3. test functions
Because the assert function only throws an error when the test fails, we cannot know whether the test fails or succeeds after the test fails. Therefore, we can organize the test into a test function. In this way, each test function executes only one unit, but one or more assertions can be called.
Function testcase (name, tests) {assert. count = 0; var successful = 0; var testcount = 0; var hassetup = typeof tests. setup = "function"; var hasteardown = typeof tests. teardown = "function"; for (VAR test in tests) {// only execute the function if (! /^ Test /. test (test) {continue;} testcount ++; try {If (hassetup) {tests. setup (); // run the setup function} tests [test] (); // run the test function output (test, "#0c0 "); // output green if (hasteardown) {tests. teardown (); // execute the demolition function} successful ++;} catch (e) {output (test + "failed:" + E. message, "# c00"); // output red and error message on the page} var color = successful = testcount? "#0c0": "# c00"; output ("<strong>" + testcount + "tests," + (testcount-successful) + "failures </strong> ", color );}
The following is the specific usage method. This test will fail because the ARR length is 5 rather than 7.
TestCase("assertTest", {setUp: function () {this.arr = [1, 2, 3, 4, 5];},"test arr length": function() {assert("arr length is 7", this.arr.length === 7);},tearDown: function () {}});
By, junjun16818