Skip to content

Instantly share code, notes, and snippets.

@mekuls
Last active April 5, 2016 04:04
Show Gist options
  • Save mekuls/8bf23b54267fa572fe7bf6f741b88aff to your computer and use it in GitHub Desktop.
Save mekuls/8bf23b54267fa572fe7bf6f741b88aff to your computer and use it in GitHub Desktop.
Javascript Quick Start

##Javascript starter app

For me, this is the minimum amount of configuration required in order to write some javascript code.

  • Make the root application directory
  • Make subfolders, one for the app and one for tests.
mkdir _app
mkdir _tests
  • Run 'npm init' and fill in everything required.
  • Add the following to the bottom of your package.json
  "dependencies": {
  },
  "devDependencies": {
    "chai": "^3.5.0",
    "gulp": "^3.9.1",
    "gulp-mocha": "^2.2.0",
    "gulp-util": "^3.0.7",
    "jshint": "^2.9.1"
  }

Then run

$> npm install

Note: In order to get chai working properly with mocha I need to run the following:

npm install mocha@* --save-dev
npm install chai@* --save-dev

Then add the following Gulpfile.js to the root directory.

var gulp = require('gulp');

var mocha = require('gulp-mocha');
var gutil = require('gulp-util');

var bases = {
	app: "_app",
	tests: "_tests"
};

gulp.task('mocha', function() {
	return gulp.src(
		[
			bases.tests + '/*.js'
		], { read: false }
	).pipe(mocha({ reporter: 'list' }))
	.on('error', gutil.log);
});

gulp.task('watch-mocha', function() {
	gulp.watch(
	[
		bases.app + '/**', 
		bases.tests + '/**'], 
	['mocha']);
});

gulp.task('default', function() {
});
``

This particular setup has a variable called 'bases', this splits your project into 2 different folders, the app folder will be watched for changes within the watch-mocha task. All tests are within the bases.tests directory, eg, 'tests/test_component.js'.

Now add some code:

app/script.js

```javascript
exports.addNumbers = function(a, b) {
    if (a == undefined || b == undefined) {
        throw Error("both values must be defined");
    }

    return a + b;
}```

tests/test_script.js

```javascript
var chai = require('chai');
chai.should() // add should to Object.prototype

describe('#addNumbers()', function() {

    it ('should return the sum of two numbers', 
            function() {
                var sut = require('../_app/script');
                var sum = sut.addNumbers(1, 3);
                sum.should.equal(4);
            }
    );

    it ('should throw if one of the numbers is undefined', 
            function() {
        
        var sut = require('../_app/script');
        var fn = (function() {sut.addNumbers(undefined, 1)});
        fn.should.throw(Error);

        var fn = (function() {sut.addNumbers(1, undefined)});
        fn.should.throw(Error);

    });
});

To run your tests using the watch runner, try

gulp watch-mocha
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment