All Projects → bignimbus → Extended Javascript Console

bignimbus / Extended Javascript Console

Licence: mit
console.expect(console).toContain('useful tools');

Programming Languages

javascript
184084 projects - #8 most used programming language

extended javascript console

better JavaScript console methods.

Welcome


contents

  1. Getting Started
  2. console.out()
  3. console.run()
  4. console.expect()
  5. console.diff()
  6. Namespace
  7. Tests
  8. Contribute
  9. Acknowledgements

getting started

xcon works as a require module or as a pojo. There is also a browser extension that will automagically load the latest xcon-min release build to any page. The extensions are still new and need to be field-tested more extensively, but I believe that this are the most logical way to deploy the latest xcon builds so that you don't have to touch your source code.

using bower:

bower install extended-javascript-console

require.js: I recommend declaring xcon last in your require path list, since you will not need to declare it as a module.

define([
	"path/to/xcon-0.6.0.min"
], function () {
// no need to declare as a parameter
/* or... */
require(["path/to/xcon-0.6.0.min"])

plain ol' JavaScript:

<script src="path/to/dist/xcon-0.6.0.min.js"></script>

console.out()

like console.log, but also prints the primitive type. Accepts any number of arguments. The last argument can contain an options hash.

console.out('hello world!');

outputs:

string:
hello world!

console.out(Math.PI, false, NaN, [1, 2, 3], {
    "can": "tell",
    "the": "difference",
    "between": "objects",
    "and": "arrays"
});

outputs:

number:
3.141592653589793 
boolean:
false
number:
NaN 
array:
[1,2,3] 
object:
{"can":"tell","the":"difference","between":"objects","and":"arrays"}

options

var someVar = {"foo": "bar"};
console.out(someVar, { // options hash is passed last
	"color": "rgba(0, 0, 255, 0.8)", // or any valid css color
    "bg": "hsv(150, 150, 150)" // or any valid css color
    "log": true, // also calls native console.  Useful for nesting complex objects
});

console.run()

calls the given function; returns and logs the result with important details. Catches errors gracefully and logs the error message. Capable of nested calls for more complex debugging and logging. Green text indicates that the function was run and returned a valid result. Black text indicates that you are not invoking a function. Red text indicates an error has occurred.


function goodFunction () {
	return "this function worked!";
}
console.run(goodFunction);

valid output


function badFunction () {
	return undefinedVariable;
}
console.run(badFunction);

error output


passing arguments

Pass all function arguments as an array as the second argument.

function multiply () {
	var product = 1, n;
	for (n = 0; n < arguments.length; n++) {
    	product *= arguments[n];
    }
    return product;
}
console.run(multiply, [2, 2, 2]);

arguments


passing context

var fakeObj = {};
function FakeConstructor () {
	this.prop = "something";
	return this;
}
fakeObj = console.run(FakeConstructor, [], fakeObj);
fakeObj.prop === "something"; // true

in the above example, fakeObj will be interpreted as this by `FakeConstructor'.


nesting calls

sometimes it helps to know what a chain of dependent functions are doing. Because console.run() returns the value of the function, you can keep eye on the output of each function in an organized way.

function mcConaughey (article) {
	return "removing " + article;
}
function carrey (topic) {
	return "makes a joke about " + topic;
}
console.run(carrey,
	[console.run(mcConaughey, ["shirt"])]
);

chaining


It can help keep track of what's going wrong in your application flow:
function carrotTop () {
	return hasNoIdeaWhatHesDoingHere;
}
console.run(carrey, 
	[console.run(mcConaughey, 
    		[console.run(carrotTop)]
    	)]
);

chain undefined


Non-functions

It is possible to pass a non-function into .run(). The value of that non-function will be logged as though you were calling .out(). Additionally, that non-function will be returned, enabling the developer to write inline console statements.

var a = console.run('a');
a === 'a' // evaluates to true
// in the console...
// string:
// a

console.expect()

unit tests in the browser console

A stripped-down collection of unit test methods that borrow heavily from jasmine.js. Developers who regularly use console.log() to debug or dirty-test their code may find that console.expect adds a more precise tool to their workflow.


console.expect(data).toEqual(comparison)

A passed test indicates that the argument passed to expect() and the argument passed to toEqual() are strictly equal - including truthy and falsy values. Works for any JavaScript data type: primitives, objects, and functions. Test results are highlighted in green (passed) or red (failed) in the console.

console.expect(4).toEqual(4);

toEqual


Failed isEqual() tests

Failed isEqual() tests will call console.diff() if both inputs are objects or both are arrays.

console.expect({
	"one": 1, "two": 2
}).toEqual({
	"one": 1, "three": 3
});

failed-object-equality


console.expect(data).toContain(comparison)

Passed test indicates that data (can be an object or array) contains comparison anywhere in its structure. This works for complex arrays and objects with nested data.

var complexObj = {
    "starbucks": {
        "coffee": "ok",
        "espresso": "pretty bad",
        "sweetDrinks": {
            "PSL": "overrated, but still good"
        }
    },
    "dunkindonuts": {
        "flavors": ["cinnamon", "french vanilla"],
        "randomNumbers": [2, 3, 4, 5, 6]
    },
    "intelligentsia": [
        {
            "yummy": true,
            "expensive": true
        }
    ]
};
console.expect(complexObj).toContain(6);

toContain


console.expect(data).toBeCloseTo(num, margin)

Passed test indicates that num will be greater than data - margin and less than data + margin.

console.expect(5).toBeCloseTo(6, 2);

toBeCloseTo


console.expect(data).toBeTruthy()

Passed test indicates a truthy value.

console.expect("I'm truthy").toBeTruthy();

toBeTruthy


console.expect(data).toBeDefined()

Passed test indicates data that is not undefined.

console.expect({}).toBeDefined();

toBeDefined


console.expect(data).toBeNull()

Passed test indicates data that is equal to null.

console.expect(null).toBeNull();

toBeNull


.not

Prepend the test method with .not to invert the test.

console.expect(Math.PI).not.toEqual(Math.PI);

notToEqual

console.expect([0, 1, 2]).not.toEqual({"0": 0, "1": 1, "2": 2});

array-object

Note: JavaScript would interpret these two blobs as identical because they are both objects, have identical keys and values. For the purposes of testing, it is anticipated that developers would not want an array and object to be considered stricty equal for the purpose of testing code. Furthermore, arrays and objects have different prototypes. For these reasons, arrays and objects with identical keys and values will not be interpreted by xcon as equal.


console.diff()

Given two objects or two arrays, tells the user whether the two arguments are equal and, if not, exactly what unique data is in each argument. Will return false if the types of both arguments do not match or if given a non-object or non-array as an argument. Works for nested objects and arrays, as well. This method is automatically called when there is a failed isEqual() test in console.expect().

var harry = {
		"mock": "yeah",
		"ing": "yeah",
		"bird": {
			"yeah": "yeah",
			"yeah": ["yeah"]
		}
	},
	lloyd = {
		"mock": "yeah",
		"annoyingSound": "eeeeehhhhhh"
	};
console.diff(harry, lloyd);

console.diff


Namespace

To ensure that xcon.js will never break native console methods, there are fallbacks in the code. If Mozilla, Webkit, Microsoft, etc. were to implement .run, .out, .diff, or .expect tomorrow, xcon would not overwrite those methods.


Tests

grunt jasmine will run the tests in the command line. Jasmine unit tests are in the tests directory.


Contribute

The package.json file is kept up-to-date and should contain all dev dependencies needed. grunt build runs all test specs in the command line and will abort if any tests are broken.

Grunt githooks is a dev dependency and will run all jasmine unit tests on every commit. To enable the git commit hook (please do), grunt githooks. Do not skip the hook!

Xcon source and test files use AMD modules via require.js. Grunt, AMDclean, and uglify are used to create production builds that do not need AMD. The project makes use of release branching for new features. See the issues section for project milestones.


Acknowledgements

Thanks to Kurt Peters and Corbin Swagerty, both of whom offered some great ideas for this project. Tanzeel Kazi also made important contributions to the expectation module.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].