michael@0: /* This Source Code Form is subject to the terms of the Mozilla Public michael@0: * License, v. 2.0. If a copy of the MPL was not distributed with this michael@0: * file, You can obtain one at http://mozilla.org/MPL/2.0/. michael@0: */ michael@0: "use strict"; michael@0: michael@0: const { dispatcher } = require("sdk/util/dispatcher"); michael@0: michael@0: exports["test dispatcher API"] = assert => { michael@0: const dispatch = dispatcher(); michael@0: michael@0: assert.equal(typeof(dispatch), "function", michael@0: "dispatch is a function"); michael@0: michael@0: assert.equal(typeof(dispatch.define), "function", michael@0: "dispatch.define is a function"); michael@0: michael@0: assert.equal(typeof(dispatch.implement), "function", michael@0: "dispatch.implement is a function"); michael@0: michael@0: assert.equal(typeof(dispatch.when), "function", michael@0: "dispatch.when is a function"); michael@0: }; michael@0: michael@0: exports["test dispatcher"] = assert => { michael@0: const isDuck = dispatcher(); michael@0: michael@0: const quacks = x => x && typeof(x.quack) === "function"; michael@0: michael@0: const Duck = function() {}; michael@0: const Goose = function() {}; michael@0: michael@0: const True = _ => true; michael@0: const False = _ => false; michael@0: michael@0: michael@0: michael@0: isDuck.define(Goose, False); michael@0: isDuck.define(Duck, True); michael@0: isDuck.when(quacks, True); michael@0: michael@0: assert.equal(isDuck(new Goose()), false, michael@0: "Goose ain't duck"); michael@0: michael@0: assert.equal(isDuck(new Duck()), true, michael@0: "Ducks are ducks"); michael@0: michael@0: assert.equal(isDuck({ quack: () => "Quaaaaaack!" }), true, michael@0: "It's a duck if it quacks"); michael@0: michael@0: michael@0: assert.throws(() => isDuck({}), /Type does not implements method/, "not implemneted"); michael@0: michael@0: isDuck.define(Object, False); michael@0: michael@0: assert.equal(isDuck({}), false, michael@0: "Ain't duck if it does not quacks!"); michael@0: }; michael@0: michael@0: exports["test redefining fails"] = assert => { michael@0: const isPM = dispatcher(); michael@0: const isAfternoon = time => time.getHours() > 12; michael@0: michael@0: isPM.when(isAfternoon, _ => true); michael@0: michael@0: assert.equal(isPM(new Date(Date.parse("Jan 23, 1985, 13:20:00"))), true, michael@0: "yeap afternoon"); michael@0: assert.equal(isPM({ getHours: _ => 17 }), true, michael@0: "seems like afternoon"); michael@0: michael@0: assert.throws(() => isPM.when(isAfternoon, x => x > 12 && x < 24), michael@0: /Already implemented for the given predicate/, michael@0: "can't redefine on same predicate"); michael@0: michael@0: }; michael@0: michael@0: require("sdk/test").run(exports);