Browse Source

added tests

master
mort 7 years ago
parent
commit
aea6238853
3 changed files with 64 additions and 2 deletions
  1. 26
    0
      index.js
  2. 2
    2
      package.json
  3. 36
    0
      test/test.js

+ 26
- 0
index.js View File

@@ -2,6 +2,26 @@ var regStr = "{{(.+)}}";
var localRegex = new RegExp(regStr);
var globalRegex = new RegExp(regStr, "g");

function expectType(type, val) {
if (typeof val !== type)
throw new TypeError("Expected "+type+", got "+typeof val);
}

function expectInstance(obj, val) {
if (!(val instanceof obj)) {
var regex = /function (.+)\(/;
var expectedName = obj.toString().match(regex)[1];

try {
var realName = val.constructor.toString().match(regex)[1];
} catch (err) {
var realName = "undefined";
}

throw new TypeError("Expected "+expectedName+", got "+realName);
}
}

function hasMultipleStatements(str) {
return (str.indexOf(";") !== -1)
}
@@ -12,6 +32,9 @@ function Func(args) {
Func.prototype = Function.prototype;

function Templish(str, vals) {
expectType("string", str);
expectInstance(Array, vals);

str = str.replace(/\s+/g, " ").replace(/}}/g, "}}\n");
this.string = str;
this.vals = vals;
@@ -48,6 +71,9 @@ function Templish(str, vals) {
}

Templish.prototype.exec = function(vals, cb) {
expectInstance(Object, vals);
expectType("function", cb);

var str = this.string;

//Prepare generic arguments

+ 2
- 2
package.json View File

@@ -1,10 +1,10 @@
{
"name": "templish",
"version": "0.0.2",
"version": "0.0.3",
"description": "HTML templating library for JS",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
"test": "mocha test"
},
"author": "Martin Dørum Nygaard",
"license": "MIT",

+ 36
- 0
test/test.js View File

@@ -0,0 +1,36 @@
var assert = require("assert");
var Templish = require("../index.js");

describe("templish", function() {
it("does basic substitution", function(done) {
var t = new Templish("{{conf.foo}}", ["conf"]);
t.exec({conf: {foo: "bar"}}, function(err, res) {
assert.equal(res, "bar");
done(err);
});
});

it("does basic async substitution", function(done) {
var t = new Templish("{{cb(null, 'hi')}}", []);
t.exec({}, function(err, res) {
assert.equal(res, "hi");
done(err);
});
});

it("does a mix of async and sync substitution", function(done) {
var t = new Templish("{{'a'}} {{cb(null, 'b')}} {{'c'}} {{cb(null, 'd')}}", []);
t.exec({}, function(err, res) {
assert.equal(res, "a b c d");
done(err);
});
});

it("doesn't break when the result of a substitution looks like a template", function(done) {
var t = new Templish("foo: {{foo}}, again: {{foo}}", ["foo"]);
t.exec({foo: "{{foo}}"}, function(err, res) {
assert.equal(res, "foo: {{foo}}, again: {{foo}}");
done(err);
});
});
});

Loading…
Cancel
Save