0

I've been trying to teach myself how to unit test my code since I'm having trouble figuring out where my errors are being generated at times. Here is a simple function that I'm testing-

var exports = module.exports = {};

exports.mike = function(num) {
    var result = num * 2;
    return result;
}

Here's what I have in my /test/test.js

var should = require('should');
var pete = require('../program');
describe('#mike()', function(){
    it('when passed a 2 should equal 4', function(){
        pete.mike(2).should.equal(4);
        });
    });

in my package.json I have

"scripts": {
    "test": "mocha"
  }

When I run npm test, everything works correctly. My question is this- what are the best practices for using unit tests? I know you can write them inline with your code but that seems like it would cause unnecessary bloat. Can they only be used by requiring them in your test.js like I did or is there a way you can run the test on a file external to it?

(I'm thinking of nodeschool for an example. I know they are somehow running what looks like unit tests on your program that you create without you having to specifically write something in your code to include the testing.)

thanks!

Jimbo
  • 81
  • 2
  • 9

1 Answers1

0

In my project, all test files are under the folder /test with the name test-NeedTestFileName.js.

And in the package.json

  "scripts": {
    "start": "node ./src/server/app",
    "build": "node build/server/server.js --install_folder .",
    "mocha": "./node_modules/.bin/mocha -u bdd -R spec --timeout 10000 ./src/server/tests/test-*.js",
    "mocha-report": "./node_modules/.bin/mocha -R xunit --timeout 10000 ./src/server/tests/test-*.js -O output=./test-results/mocha.xml",
    "karma": "node node_modules/karma/bin/karma start",
    "test": "npm run mocha-report && npm run karma",

When I want to run unit test, just run npm run mocha. To get the unit test report, will run npm test.

zangw
  • 43,869
  • 19
  • 177
  • 214
  • do you have to module.export your functions and then require them in your tests like I did? – Jimbo Jan 14 '16 at 14:18