From e57549cdb20abf83353875c4b697da8fa78fe3cd Mon Sep 17 00:00:00 2001 From: Bryan Berry Date: Mon, 16 Nov 2009 23:33:49 +0000 Subject: most tests for Karma.karma and Karma.kMedia pass --- diff --git a/js/karma.js b/js/karma.js index bd60c29..6ab294b 100755 --- a/js/karma.js +++ b/js/karma.js @@ -6,14 +6,13 @@ if(!this.exports) { var Karma = exports.Karma = function (options) { - if ( Karma.KarmaRoot) { - return Karma.KarmaRoot; + if ( Karma.karma.initialized === true ) { + return Karma.karma; } else { - return Karma.create(Karma.karma).init(options); + return Karma.karma.init(options); } }; -Karma.KarmaRoot = null; //helper functions, all in the Karma namespace @@ -91,32 +90,32 @@ Karma.makeSurfaces = function (surfaces){ Karma.karma = { locale : undefined, _localized : false, + _assetPath : "../assets/", _localePath : "", images : [], - videos : [], sounds : [], + surfaces : [], svgs : [], + videos : [], + initialized : false, statusDiv: undefined, _counters : { total : 0, errors : 0, loaded : 0}, //init initializes all the assets passed to Karma, that's it //it returns 'this' so it can be used for function chaining init: function(options) { - this.name = "karma"; - Karma.KarmaRoot = this; + this.initialized = true; //set up message that show count of assets loaded + //and has an ordered list to append error messages to var loaderDiv = document.createElement('div'); - loaderDiv.innerHTML = '
Karma is \ - loading ...
'; + loaderDiv.setAttribute('id', 'karma-status'); + loaderDiv.innerHTML = 'Karma is \ + loading ...
' + + '
    '; document.body.appendChild(loaderDiv); this.statusDiv = document.getElementById("karma-loader"); - //create an ordered list to hold any error messages that pop-up - var ol = document.createElement('ol'); - ol.setAttribute('id', 'errorList'); - this.statusDiv.appendChild(ol); - //regular expression that matches the name of aprivate property // the karma object @@ -141,7 +140,7 @@ Karma.karma = { if (this.isValidLocale(options[option])){ this.locale = this.normalizeLocale(options[option]); this._localized = true; - options._localePath = Karma.computeLocalePath(this.locale); + this._localePath = Karma.computeLocalePath(this.locale); } else { throw new Error("locale provided to karma.init() is invalid"); } @@ -175,7 +174,7 @@ Karma.karma = { //ready checks to see if all assets loaded, then runs lesson code ready : function( cb ) { that = this; - if (!Karma.KarmaRoot){ + if (Karma.karma.initialized !== true){ throw new Error("Karma.karma not initialized"); } @@ -210,6 +209,7 @@ Karma.karma = { if (errorMsg) { var liError = document.createElement('li'); liError.innerText = errorMsg; + console.log(errorMsg); var errorList = document.getElementById('errorList'); errorList.appendChild(liError); } @@ -234,6 +234,26 @@ Karma.karma = { return locale.length > 2 ? "" + lang + divider + country : lang; }, + //unit test suite uses this function + reset : function () { + if (this.statusDiv){ + var karmaStatus = document.getElementById('karma-status'); + karmaStatus.parentElement.removeChild(karmaStatus); + } + this._assetPath = "assets/", + this.locale = undefined, + this._localized = false, + this._localePath = "", + this.images = [], + this.surfaces = [], + this.sounds = [], + this.svgs = [], + this.videos = [], + this.initialized = false, + this.statusDiv= undefined, + this._counters = { total : 0, errors : 0, loaded : 0}; + return this; + }, }; @@ -242,15 +262,15 @@ Karma.kMedia = { name : "", file : "", path : "", - localized : false, + _localized : false, _type : "", media : undefined, init : function (asset) { - Karma.KarmaRoot._counters.total++; + Karma.karma._counters.total++; - asset.localized = asset.localized || false; + asset._localized = asset._localized || false; if (asset.name === undefined || asset.file === undefined){ throw new Error("properties name and file have to be defined"); @@ -283,56 +303,54 @@ Karma.kMedia = { } } - if(Karma.isLocalized(asset.localized)){ - this.localized = asset.localized; - this.path = Karma.computeLocalePath(Karma.KarmaRoot.locale) + - this.type + "s/"; + if(Karma.isLocalized(asset._localized)){ + this._localized = asset._localized; + this.path = Karma.karma._localePath + + this._type + "s/"; + } else { + this.path = Karma.karma._assetPath + + this._type + "s/"; } //IMPORTANT: This one magic line loads the file this.media.src = this.src = this.path + this.file; //add event handlers - this.addEventHandlers(this); + this.addEventHandlers(); return this; }, - addEventHandlers : function (kmedia) { + addEventHandlers : function () { var elemKarma = document.getElementById('karma-loader'); - kmedia.media.addEventListener( + var that = this; + that.media.addEventListener( "load", function (e) { - Karma.KarmaRoot._counters.loaded++; - Karma.KarmaRoot.updateStatus(); - kmedia.status = "loaded";}, false); - kmedia.media.addEventListener( + Karma.karma._counters.loaded++; + Karma.karma.updateStatus(); + that.status = "loaded";}, false); + that.media.addEventListener( "error", function (e) { Karma.karma._counters.errors++; - kmedia.status = "error"; - var errorMsg = "Error: " + kmedia._type.toUpperCase() + - " " + kmedia.name + " cannot be loaded."; - Karma.KarmaRoot.updateStatus(errorMsg); + that.status = "error"; + var errorMsg = "Error: " + that._type.toUpperCase() + + " " + that.name + " cannot be loaded."; + Karma.karma.updateStatus(errorMsg); }, false); - kmedia.media.addEventListener( + that.media.addEventListener( "abort", function (e) { - kmedia.status = "aborted"; - var errorMsg = "ABORT: " + kmedia._type.toUpperCase() + - " " + kmedia.name + " loading was aborted."; - Karma.KarmaRoot.updateStatus(errorMsg); + that.status = "aborted"; + var errorMsg = "ABORT: " + that._type.toUpperCase() + + " " + that.name + " loading was aborted."; + Karma.karma.updateStatus(errorMsg); }, false); }, - //cleans up the stuff that init creates - //used in unit testing - cleanup : function () { - var karmaLoader = document.getElementById('karma-loader'); - //karmaLoader.parent.remove - - }, + }; Karma.surface = { @@ -368,11 +386,13 @@ Karma.isValidType = function (type){ Karma.isLocalized = function (boolLocalized) { if (typeof boolLocalized === "boolean" ) { if(boolLocalized === true && - Karma.KarmaRoot.locale === undefined){ + Karma.karma.locale === undefined){ throw new Error("You cannot localize a media asset" + " if the global locale for Karma isn't set"); - } else { + } else if (boolLocalized === true) { return true; + } else { + return false; } } else if (typeof boolLocalized === undefined){ return false; @@ -382,7 +402,8 @@ Karma.isLocalized = function (boolLocalized) { }; Karma.computeLocalePath = function(locale) { - return "../assets/" + locale + "/"; + return Karma.karma._assetPath + locale + "/"; }; + diff --git a/js/qunit.js b/js/qunit.js index 2656698..b7ee538 100755 --- a/js/qunit.js +++ b/js/qunit.js @@ -13,14 +13,14 @@ var QUnit = { // Initialize the configuration options - init: function init() { + init: function() { config = { stats: { all: 0, bad: 0 }, moduleStats: { all: 0, bad: 0 }, started: +new Date, blocking: false, + autorun: false, assertions: [], - pollution: [], filters: [], queue: [] }; @@ -43,7 +43,7 @@ var QUnit = { }, // call on start of module test to prepend name to all tests - module: function module(name, lifecycle) { + module: function(name, testEnvironment) { config.currentModule = name; synchronize(function() { @@ -52,15 +52,34 @@ var QUnit = { } config.currentModule = name; - config.moduleLifecycle = lifecycle; + config.moduleTestEnvironment = testEnvironment; config.moduleStats = { all: 0, bad: 0 }; - QUnit.moduleStart( name ); + QUnit.moduleStart( name, testEnvironment ); }); }, + + asyncTest: function(testName, expected, callback) { + if ( arguments.length === 2 ) { + callback = expected; + expected = 0; + } + + QUnit.test(testName, expected, callback, true); + }, - test: function test(testName, callback) { - var name = testName, lifecycle, testEnvironment = {}; + test: function(testName, expected, callback, async) { + var name = testName, testEnvironment, testEnvironmentArg; + + if ( arguments.length === 2 ) { + callback = expected; + expected = null; + } + // is 2nd argument a testEnvironment? + if ( expected && typeof expected === 'object') { + testEnvironmentArg = expected; + expected = null; + } if ( config.currentModule ) { name = config.currentModule + " module: " + name; @@ -73,23 +92,39 @@ var QUnit = { synchronize(function() { QUnit.testStart( testName ); - lifecycle = extend({ + testEnvironment = extend({ setup: function() {}, teardown: function() {} - }, config.moduleLifecycle); + }, config.moduleTestEnvironment); + if (testEnvironmentArg) { + extend(testEnvironment,testEnvironmentArg); + } + // allow utility functions to access the current test environment + QUnit.current_testEnvironment = testEnvironment; + config.assertions = []; config.expected = null; + + if ( arguments.length >= 3 ) { + config.expected = callback; + callback = arguments[2]; + } + try { if ( !config.pollution ) { saveGlobal(); } - lifecycle.setup.call(testEnvironment); + testEnvironment.setup.call(testEnvironment); } catch(e) { QUnit.ok( false, "Setup failed on " + name + ": " + e.message ); } + if ( async ) { + QUnit.stop(); + } + try { callback.call(testEnvironment); } catch(e) { @@ -108,13 +143,13 @@ var QUnit = { synchronize(function() { try { checkPollution(); - lifecycle.teardown.call(testEnvironment); + testEnvironment.teardown.call(testEnvironment); } catch(e) { QUnit.ok( false, "Teardown failed on " + name + ": " + e.message ); } try { - reset(); + QUnit.reset(); } catch(e) { fail("reset() failed, following Test " + name + ", exception and reset fn follows", e, reset); } @@ -194,6 +229,7 @@ var QUnit = { } else { for ( var i = 0; i < config.assertions.length; i++ ) { if ( !config.assertions[i].result ) { + bad++; config.stats.bad++; config.moduleStats.bad++; } @@ -221,7 +257,7 @@ var QUnit = { /** * Specify the number of expected assertions to gurantee that failed test (no assertions are run at all) don't slip through. */ - expect: function expect(asserts) { + expect: function(asserts) { config.expected = asserts; }, @@ -229,7 +265,7 @@ var QUnit = { * Asserts true. * @example ok( "asdfasdf".length > 5, "There must be at least 5 chars" ); */ - ok: function ok(a, msg) { + ok: function(a, msg) { QUnit.log(a, msg); config.assertions.push({ @@ -250,7 +286,7 @@ var QUnit = { * @param Object expected * @param String message (optional) */ - equals: function equals(actual, expected, message) { + equals: function(actual, expected, message) { push(expected == actual, actual, expected, message); }, @@ -258,7 +294,7 @@ var QUnit = { push(QUnit.equiv(a, b), a, b, message); }, - start: function start() { + start: function() { // A slight delay, to avoid any current callbacks if ( window.setTimeout ) { window.setTimeout(function() { @@ -275,13 +311,13 @@ var QUnit = { } }, - stop: function stop(timeout) { + stop: function(timeout) { config.blocking = true; if ( timeout && window.setTimeout ) { config.timeout = window.setTimeout(function() { QUnit.ok( false, "Test timed out" ); - start(); + QUnit.start(); }, timeout); } }, @@ -289,7 +325,7 @@ var QUnit = { /** * Resets the test setup. Useful for tests that modify the DOM. */ - reset: function reset() { + reset: function() { if ( window.jQuery ) { jQuery("#main").html( config.fixture ); jQuery.event.global = {}; @@ -305,7 +341,7 @@ var QUnit = { * @param DOMElement elem * @param String type */ - triggerEvent: function triggerEvent( elem, type, event ) { + triggerEvent: function( elem, type, event ) { if ( document.createEvent ) { event = document.createEvent("MouseEvents"); event.initMouseEvent(type, true, true, elem.ownerDocument.defaultView, @@ -317,13 +353,18 @@ var QUnit = { } }, + // Safe object type checking + is: function( type, obj ) { + return Object.prototype.toString.call( obj ) === "[object "+ type +"]"; + }, + // Logging callbacks - done: function done(failures, total) {}, - log: function log(result, message) {}, - testStart: function testStart(name) {}, - testDone: function testDone(name, failures, total) {}, - moduleStart: function moduleStart(name) {}, - moduleDone: function moduleDone(name, failures, total) {} + done: function(failures, total) {}, + log: function(result, message) {}, + testStart: function(name) {}, + testDone: function(name, failures, total) {}, + moduleStart: function(name, testEnvironment) {}, + moduleDone: function(name, failures, total) {} }; // Maintain internal state @@ -346,6 +387,9 @@ var config = { GETParams.splice( i, 1 ); i--; config.noglobals = true; + } else if ( GETParams[i].search('=') > -1 ) { + GETParams.splice( i, 1 ); + i--; } } @@ -366,11 +410,17 @@ if ( typeof exports === "undefined" || typeof require === "undefined" ) { exports.QUnit = QUnit; } +if ( typeof document === "undefined" || document.readyState === "complete" ) { + config.autorun = true; +} + addEvent(window, "load", function() { // Initialize the config, saving the execution queue - var queue = config.queue; + var oldconfig = extend({}, config); QUnit.init(); - config.queue = queue; + extend(config, oldconfig); + + config.blocking = false; var userAgent = id("qunit-userAgent"); if ( userAgent ) { @@ -396,7 +446,7 @@ addEvent(window, "load", function() { toolbar.appendChild( filter ); var label = document.createElement("label"); - label.setAttribute("for", "filter-pass"); + label.setAttribute("for", "qunit-filter-pass"); label.innerHTML = "Hide passed tests"; toolbar.appendChild( label ); @@ -415,7 +465,7 @@ addEvent(window, "load", function() { toolbar.appendChild( missing ); label = document.createElement("label"); - label.setAttribute("for", "filter-missing"); + label.setAttribute("for", "qunit-filter-missing"); label.innerHTML = "Hide missing tests (untested code is broken code)"; toolbar.appendChild( label ); } @@ -429,7 +479,7 @@ addEvent(window, "load", function() { config.ajaxSettings = window.jQuery.ajaxSettings; } - start(); + QUnit.start(); }); function done() { @@ -450,6 +500,8 @@ function done() { return; } + config.autorun = true; + // Log the last module results if ( config.currentModule ) { QUnit.moduleDone( config.currentModule, config.moduleStats.bad, config.moduleStats.all ); @@ -516,6 +568,10 @@ function push(result, actual, expected, message) { function synchronize( callback ) { config.queue.push( callback ); + + if ( config.autorun && !config.blocking ) { + process(); + } } function process() { @@ -529,7 +585,7 @@ function saveGlobal() { if ( config.noglobals ) { for ( var key in window ) { - config.pollution.push(key); + config.pollution.push( key ); } } } @@ -538,24 +594,32 @@ function checkPollution( name ) { var old = config.pollution; saveGlobal(); - if ( config.pollution.length > old.length ) { - ok( false, "Introduced global variable(s): " + diff(old, config.pollution).join(", ") ); + var newGlobals = diff( old, config.pollution ); + if ( newGlobals.length > 0 ) { + ok( false, "Introduced global variable(s): " + newGlobals.join(", ") ); config.expected++; } -} -function diff( clean, dirty ) { - var results = []; + var deletedGlobals = diff( config.pollution, old ); + if ( deletedGlobals.length > 0 ) { + ok( false, "Deleted global variable(s): " + deletedGlobals.join(", ") ); + config.expected++; + } +} - for ( var i = 0; i < dirty.length; i++ ) { - for ( var c = 0; c < clean.length; c++ ) { - if ( clean[c] === dirty[i] ) { - results.push( clean[c] ); +// returns a new Array with the elements that are in a but not in b +function diff( a, b ) { + var result = a.slice(); + for ( var i = 0; i < result.length; i++ ) { + for ( var j = 0; j < b.length; j++ ) { + if ( result[i] === b[j] ) { + result.splice(i, 1); + i--; + break; } } } - - return results; + return result; } function fail(message, exception, callback) { @@ -604,13 +668,13 @@ QUnit.equiv = function () { // Determine what is o. function hoozit(o) { - if (o.constructor === String) { + if (QUnit.is("String", o)) { return "string"; - } else if (o.constructor === Boolean) { + } else if (QUnit.is("Boolean", o)) { return "boolean"; - } else if (o.constructor === Number) { + } else if (QUnit.is("Number", o)) { if (isNaN(o)) { return "nan"; @@ -626,24 +690,24 @@ QUnit.equiv = function () { return "null"; // consider: typeof [] === object - } else if (o instanceof Array) { + } else if (QUnit.is( "Array", o)) { return "array"; // consider: typeof new Date() === object - } else if (o instanceof Date) { + } else if (QUnit.is( "Date", o)) { return "date"; // consider: /./ instanceof Object; // /./ instanceof RegExp; // typeof /./ === "function"; // => false in IE and Opera, // true in FF and Safari - } else if (o instanceof RegExp) { + } else if (QUnit.is( "RegExp", o)) { return "regexp"; } else if (typeof o === "object") { return "object"; - } else if (o instanceof Function) { + } else if (QUnit.is( "Function", o)) { return "function"; } else { return undefined; @@ -834,21 +898,31 @@ QUnit.jsDump = (function() { this.parsers.error; }, typeOf:function( obj ) { - var type = typeof obj, - f = 'function';//we'll use it 3 times, save it - return type != 'object' && type != f ? type : - !obj ? 'null' : - obj.exec ? 'regexp' :// some browsers (FF) consider regexps functions - obj.getHours ? 'date' : - obj.scrollBy ? 'window' : - obj.nodeName == '#document' ? 'document' : - obj.nodeName ? 'node' : - obj.item ? 'nodelist' : // Safari reports nodelists as functions - obj.callee ? 'arguments' : - obj.call || obj.constructor != Array && //an array would also fall on this hack - (obj+'').indexOf(f) != -1 ? f : //IE reports functions like alert, as objects - 'length' in obj ? 'array' : - type; + var type; + if ( obj === null ) { + type = "null"; + } else if (typeof obj === "undefined") { + type = "undefined"; + } else if (QUnit.is("RegExp", obj)) { + type = "regexp"; + } else if (QUnit.is("Date", obj)) { + type = "date"; + } else if (QUnit.is("Function", obj)) { + type = "function"; + } else if (QUnit.is("Array", obj)) { + type = "array"; + } else if (QUnit.is("Window", obj) || QUnit.is("global", obj)) { + type = "window"; + } else if (QUnit.is("HTMLDocument", obj)) { + type = "document"; + } else if (QUnit.is("HTMLCollection", obj) || QUnit.is("NodeList", obj)) { + type = "nodelist"; + } else if (/^\[object HTML/.test(Object.prototype.toString.call( obj ))) { + type = "node"; + } else { + type = typeof obj; + } + return type; }, separator:function() { return this.multiline ? this.HTML ? '
    ' : '\n' : this.HTML ? ' ' : ' '; diff --git a/tests/.#tests.js b/tests/.#tests.js deleted file mode 120000 index 4ddf3c8..0000000 --- a/tests/.#tests.js +++ /dev/null @@ -1 +0,0 @@ -hitman@hitman.15668:1258379610 \ No newline at end of file diff --git a/tests/index.html b/tests/index.html index 03ca2da..fb2de52 100755 --- a/tests/index.html +++ b/tests/index.html @@ -9,7 +9,7 @@ - + diff --git a/tests/tests.js b/tests/js/tests.js index 7ce64d0..e83b182 100755 --- a/tests/tests.js +++ b/tests/js/tests.js @@ -11,17 +11,11 @@ } }; - var shouldError = function ( cb, expectedError ){ + var shouldError = function ( cb ){ try { cb(); - } catch (e){ - if (expectedError){ - if (e.name === expectedError.name) { - return true; - } else { - return false; - } - } + } + catch (e) { return true; } return false; @@ -31,17 +25,11 @@ return !shouldError( cb ); }; - var getFile = function (fileName){ - var xhr = new XMLHttpRequest(); - xhr.open('GET', options.images[0].file, false); - xhr.send(''); - return xhr; - }; - - module("Module Helpers"); + test("Basic Requirements", function() { + expect(5); ok( Karma, "Karma library loaded"); ok( Array.prototype.push, "Array.push()" ); ok( Function.prototype.apply, "Function.apply()" ); @@ -50,6 +38,7 @@ }); test("Karma.create", function(){ + expect(2); var mock = {}; //test against empty object same(Karma.create({}), mock, "doesn't match empty object"); @@ -60,6 +49,8 @@ }); test("Karma.clone", function(){ + expect(2); + var mock = { name: "foo", age: 30, children : ["adrian", "sheila", "stephanie"], spouse: { wife: "Marie"}}; same(Karma.clone(mock), mock, @@ -71,6 +62,8 @@ }); test("Karma.objectPlus", function(){ + expect(2); + var warrior = { name : "conan", age : 30, dance : true}; var oldProto = warrior.__proto__; var ninja = { dance : false, tattoo : true}; @@ -83,6 +76,7 @@ }); test("Karma.copyObjectPlus", function(){ + expect(2); var warrior = { name : "conan", age : 30, dance : true}; var copyWarrior = Karma.clone(warrior); var ninja = { dance : false, name : "Yoshi"}; @@ -100,89 +94,106 @@ module("Module Karma core library"); - test("Karma()", function () { - - same(Karma.create(Karma.karma).init(), Karma(), - "Karma() w/ no arguments returns the karma object"); - }); - - - test("Karma.karma", function () { - var options; - var karma1 = Karma.create(Karma.karma); + test("Karma()", function () { + expect(2); + var karma1 = Karma(); + ok(Karma.karma.initialized === true, + "Karma() sets initialized property on Karma.karma"); + var karma2 = Karma(); + ok (karma1 === karma2, "Karma() only allows one instance of Karma.karma"); }); test("Karma.karma.init()", function() { + expect(5); + ok( + shouldNotError( + function(){ + Karma.karma.init(); + }), "Karma.karma.init() does not throw errors when " + + "initialized with no options"); - Karma.KarmaRoot = undefined; - var karma1 = Karma.create(Karma.karma).init(); - ok(Karma.KarmaRoot , "Karma.karma.init() creates KarmaRoot object"); + Karma.karma.reset(); ok(shouldError(function () { - karma1.init({locale : "foo"});}), + Karma.karma.init({locale : "foo"});}), "emits error on invalid locale"); + Karma.karma.reset(); + var goodOptions = {locale : "en", images : [{ name: "chimp", file : 'chimp.png' }], sounds : [{ name: "correct", file : 'correct.ogg'}], surfaces : [{ name: "test", canvas : 'testCanvas'}]}; - - var karma5 = Karma.create(Karma.karma); - ok(shouldNotError(function () { karma5.init(goodOptions);}), + + ok(shouldNotError(function () { Karma.karma.init(goodOptions);}), "accepts good options"); + Karma.karma.reset(); var badOptions = {locale : "en", images : [{ name: "chimp", file : 'chimp.png' }], sounds : [{ name: "correct", file : 'notthere.ogg'}], surfaces : [{ name: "", canvas : 'noCanvas'}]}; - ok(shouldError(function () { karma5.init(badOptions); }), + ok(shouldError(function () { Karma.karma.init(badOptions); }), "Rejects bad options"); + Karma.karma.reset(); + //test that init won't overwrite private properties - var karma6 = Karma.create(Karma.karma).init({_counters : { errors : 500}}); - ok(karma6._counters.errors !== 500, "Private property not overwritten"); + Karma.karma.init({_counters : { errors : 500}}); + ok(Karma.karma._counters.errors !== 500, "Private property not overwritten"); + + Karma.karma.reset(); }); test("Karma.karma.ready()", function () { - Karma.KarmaRoot = undefined; - var karma3 = Karma.create(Karma.karma); - ok(shouldError(function () {karma3.ready();}), "Uninitialized karma instance " + + expect(3); + ok(shouldError(function () {Karma.karma.ready();}), "Uninitialized karma instance " + "generates error on .ready()"); - karma3 = Karma.create(Karma.karma).init().ready(); + Karma.karma.reset(); + + Karma.karma.init().ready(); var starterMsg = document.getElementById('starterMsg'); ok(starterMsg, "Karma.karma.ready() with no callback displays starter msg"); //clean up document.body.removeChild(starterMsg); + Karma.karma.reset(); var ninjaName = "Bruce Lee"; var testCb = function () { ninjaName = "Chuck Norris";}; - var karma4 = Karma.create(Karma.karma).init().ready(testCb); + Karma.karma.init().ready(testCb); ok (ninjaName === "Chuck Norris", "ready() calls callback"); - - //test that callback isn't called while asset isn't ready yet - ninjaName = "Bruce Lee"; - karma4 = Karma.create(Karma.karma).init(); - karma4._counters.total = 5000; - karma4.ready(testCb); - ok( ninjaName === "Bruce Lee", "callback not called before all assets loaded"); - karma4._counters.total = 0; - - //wait for callback to be called by ready - setTimeout(function() { - ok (ninjaName === "Chuck Norris", - "ready() calls callback after assets loaded");}, - 200); + Karma.karma.reset(); }); + asyncTest("Karma.karma.ready() check callback execution", + function(){ + //test that callback isn't called while asset isn't ready yet + expect(2); + var ninjaName = "Bruce Lee"; + var testCb = function () { ninjaName = "Chuck Norris";}; + Karma.karma.reset().init(); + Karma.karma._counters.total = 5000; + Karma.karma.ready(testCb); + ok( ninjaName === "Bruce Lee", "callback not called before all assets loaded"); + Karma.karma._counters.total = 0; + + //wait for callback to be called by ready + setTimeout(function() { + ok (ninjaName === "Chuck Norris", + "ready() calls callback after assets loaded"); + Karma.karma.reset(); + start();}, + 200); + }); test("karma.isValidLocale(locale)", function () { @@ -190,7 +201,7 @@ * before dash or underscore * */ - + expect(4); // test valid locale ok(Karma.karma.isValidLocale("en"), "Valid locale option accepted"); @@ -216,7 +227,7 @@ * * don't choke on locale w/ only two letters */ - + expect(3); ok (Karma.karma.normalizeLocale("EN-us") === "en_US", "lowercase, uppercase, and dash properly changed"); ok (Karma.karma.normalizeLocale("en_US") === "en_US", @@ -234,17 +245,17 @@ * make sure returns path "../assets/locale_name/" * */ - + expect(2); ok(Karma.computeLocalePath("en_US") === - "../assets/en_US/", "computes correct path"); + "assets/en_US/", "computes correct path"); ok(Karma.computeLocalePath("es") === - "../assets/es/", "computes correct path"); + "assets/es/", "computes correct path"); }); test("Karma.kMedia", function (){ - + expect(0); }); @@ -272,6 +283,7 @@ test("Karma.kMedia.init({})", function () { + expect(1); var kMock = Karma.create(Karma.kMedia); ok(shouldError( function(){ @@ -279,102 +291,94 @@ }), "Throw error if _type, name, or file not specified"); }); - var kMedia1 = Karma.create(Karma.kMedia); - - if(Karma.KarmaRoot){ - delete Karma.KarmaRoot; - } - - Karma.KarmaRoot = Karma.create(Karma.karma).init({}); - var oldErrors = Karma.KarmaRoot._counters.errors; - var oldTotal = Karma.KarmaRoot._counters.total; - kMedia1.init({name: "notthere", _type : "image", - file: "notthere.png"}); //have to do this asynchronously let the error event propagate - setTimeout( - function(){ - - - test("Karma.kMedia.init(/* bad options */)", - function (){ - ok(kMedia1.status === "error", "bad file name produces error"); - ok(Karma.KarmaRoot._counters.errors === oldErrors + 1 , - "Error counter was incremented on load error"); - ok(Karma.KarmaRoot._counters.total === oldTotal + 1 , - "Total Assets counter was incremented"); - var errorMsg = $('#karma-loader>ol>li').text(); - ok(errorMsg === "ERROR: File notthere.png could not be loaded", - "correct error message appended"); + asyncTest("Karma.kMedia.init(/* bad options */)", + function(){ + expect(4); + var kMedia1 = Karma.create(Karma.kMedia); + Karma.karma.reset().init(); + var oldErrors = Karma.karma._counters.errors; + var oldTotal = Karma.karma._counters.total; + kMedia1.init({name: "notthere", _type : "image", + file: "notthere.png"}); + setTimeout( + function (){ + ok(kMedia1.status === "error", "bad file name produces error"); + ok(Karma.karma._counters.errors === oldErrors + 1 , + "Error counter was incremented on load error"); + ok(Karma.karma._counters.total === oldTotal + 1 , + "Total Assets counter was incremented"); + var errorMsg = $('#karma-status>ol>li').text(); + var regex = new RegExp('error', 'i'); + ok(regex.test(errorMsg), + "error message appended"); + Karma.karma.reset(); + start(); + },100); }); - }, 100); - oldErrors = Karma.KarmaRoot._counters.errors; - oldTotal = Karma.KarmaRoot._counters.total; - kMock = { name: "chimp", _type: "image", file: "happyMonkey"}; - kMedia1 = Karma.create(Karma.kMedia).init(kMock); - setTimeout( - function(){ - test("Karma.kMedia.init(/* good options */)", - function () { + asyncTest("Karma.kMedia.init(/* good options */)", + function(){ + expect(3); + Karma.karma.reset().init(); + oldErrors = Karma.karma._counters.errors; + oldTotal = Karma.karma._counters.total; + kMock = { name: "chimp", _type: "image", file: "happyMonkey.jpg"}; + kMedia1 = Karma.create(Karma.kMedia).init(kMock); + + setTimeout( + function () { ok(kMedia1.status === "loaded", "Good file is loaded"); - ok(Karma.KarmaRoot.counterrors === oldErrors, + ok(Karma.karma._counters.errors === oldErrors, "Error counter not incremented"); - ok(Karma.KarmaRoot._counters.total === oldTotal + 1 , - "Total Assets counter was incremented");}); - }, 100); + ok(Karma.karma._counters.total === oldTotal + 1 , + "Total Assets counter was incremented"); + Karma.karma.reset(); + start(); + }, 100); + }); - kMock = Karma.create(Karma.kMedia); - Karma.karma.locale = undefined; test("Karma.kMedia.init( /* localize an asset when locale not set */)", function(){ + expect(1); + var kMock = Karma.create(Karma.kMedia); + Karma.karma.locale = undefined; + ok(shouldError( function () { - kMock.init({ name: 'esMonkey', file: 'HappyMonkey.jpg', + kMock.init({ name: 'esMonkey', file: 'happyMonkey.jpg', _type: 'image', localized: true }); }), "You can't localize an asset if the locale isn't defined for your lesson"); }); - - - /* kMock = Karma.create(Karma.kMedia); - oldErrors = Karma.karma._counters.errors; - oldTotal = Karma.karma._counters.total; - kMock.init({ name : 'trigger', file : 'trigger.ogg', - _type : "sound", localized : true}); - - setTimeout( - function(){ - test("Karma.kMedia.init( localized asset)", - function () { - ok(kMock.status === "error", "Asset has status properly set to error"); - ok(Karma.karma._counters.errors === oldErrors + 1, - "Loading a localized file emits an error event if a localized version doesn't exist"); - ok(Karma.karma._counters.total === oldTotal + 1 , - "Total Assets counter was incremented"); - }); - },100); - */ - - kMock = Karma.create(Karma.kMedia); - oldErrors = Karma.karma._counters.errors; - oldTotal = Karma.karma._counters.total; - kMock.init({ name : 'monkey', file : 'happyMonkey.jpg', - _type : "image", localized : true}); - - setTimeout( - function(){ - test( function(){ - ok(Karma.KarmaRoot._counters.errors === oldErrors, - "Properly loads localized file"); - ok(Karma.KarmaRoot._counters.total === oldTotal + 1 , - "Total Assets counter was incremented"); - }); - }, 100); + + + + asyncTest("Karma.kMedia.init() w/ localized file", + function(){ + expect(2); + + Karma.karma.reset().init(); + kMock = Karma.create(Karma.kMedia); + oldErrors = Karma.karma._counters.errors; + oldTotal = Karma.karma._counters.total; + kMock.init({ name : 'monkey', file : 'happyMonkey.jpg', + _type : "image", localized : true}); + + setTimeout( + function(){ + ok(Karma.karma._counters.errors === oldErrors, + "Properly loads localized file"); + ok(Karma.karma._counters.total === oldTotal + 1 , + "Total Assets counter was incremented"); + Karma.karma.reset(); + }, 100); + }); @@ -387,29 +391,25 @@ * produce error if item is localized but not * locale isn't set for karma object */ - Karma.KarmaRoot.locale = "en"; - ok(Karma.isLocalized(true), - "handles true string value"); - ok(Karma.isLocalized(false), - "handles false string value"); - ok(shouldError(function(){ - Karma.isLocalized("true");}), - "rejects non-boolean value"); - - if (Karma.KarmaRoot === undefined) { - Karma.KarmaRoot = {}; - } - - Karma.KarmaRoot.locale = undefined; - - ok(shouldError(function(){ - Karma.isLocalized(true); - }), - "Emits error if item is localized but Karma instance isn't"); + expect(4); + + Karma.karma.locale = "en"; + ok(Karma.isLocalized(true), + "handles true string value"); + ok(Karma.isLocalized(false), + "handles false string value"); + ok(shouldError(function(){ + Karma.isLocalized("true");}), + "rejects non-boolean value"); + + Karma.karma.locale = undefined; + ok(shouldError(function(){ + Karma.isLocalized(true); + }), + "Emits error if item is localized but Karma instance isn't"); }); - }); \ No newline at end of file -- cgit v0.9.1