convert.test.js (1359B)
1 var assert = require('assert'); 2 var typed = require('../typed-function'); 3 4 describe('convert', function () { 5 6 before(function () { 7 typed.conversions = [ 8 {from: 'boolean', to: 'number', convert: function (x) {return +x;}}, 9 {from: 'boolean', to: 'string', convert: function (x) {return x + '';}}, 10 {from: 'number', to: 'string', convert: function (x) {return x + '';}}, 11 { 12 from: 'string', 13 to: 'Date', 14 convert: function (x) { 15 var d = new Date(x); 16 return isNaN(d.valueOf()) ? undefined : d; 17 }, 18 fallible: true // TODO: not yet supported 19 } 20 ]; 21 }); 22 23 after(function () { 24 // cleanup conversions 25 typed.conversions = []; 26 }); 27 28 it('should convert a value', function() { 29 assert.strictEqual(typed.convert(2, 'string'), '2'); 30 assert.strictEqual(typed.convert(true, 'string'), 'true'); 31 assert.strictEqual(typed.convert(true, 'number'), 1); 32 }); 33 34 it('should return same value when conversion is not needed', function () { 35 assert.strictEqual(typed.convert(2, 'number'), 2); 36 assert.strictEqual(typed.convert(true, 'boolean'), true); 37 }); 38 39 it('should throw an error when no conversion function is found', function() { 40 assert.throws(function () {typed.convert(2, 'boolean')}, /Error: Cannot convert from number to boolean/); 41 }); 42 });