What's the difference between assertion library, testing framework and testing environment in javascript?

Nader picture Nader · Sep 5, 2014 · Viewed 19.7k times · Source

Chai is an assertion library.

Mocha and Jasmine are testing frameworks.

and Karma is a testing environment.

I've already read Difference between available testing frameworks: mocha, chai, karma, jasmine, should.js etc.

Answer

Zoey Mertes picture Zoey Mertes · Sep 5, 2014

Assertion libraries are tools to verify that things are correct.
This makes it a lot easier to test your code, so you don't have to do thousands of if statements.
Example (using should.js and Node.js assert module):

var output = mycode.doSomething();
output.should.equal('bacon'); //should.js
assert.eq(output, 'bacon'); //node.js assert

// The alternative being:
var output = mycode.doSomething();
if (output !== 'bacon') {
  throw new Error('expected output to be "bacon", got '+output);
}

Testing frameworks are used to organize and execute tests.
Mocha and Jasmine are two popular choices (and they're actually kinda similar).
Example (using mocha with should.js here):

describe('mycode.doSomething', function() {
  it ('should work', function() {
    var output = mycode.doSomething();
    output.should.equal('bacon');     
  });
  it ('should fail on an input', function() {
    var output = mycode.doSomething('a input');
    output.should.be.an.Error;
  });
});

Testing Environments are the places where you run your tests.

Karma is a bit of an edge case, in the sense that it's kind of a one off tool, not many like it. Karma works by running your unit tests inside of browsers (defaulting to PhantomJS, a headless WebKit browser), to allow you to test browser-based JavaScript code.

Frameworks like Mocha and Jasmine work both in the browser and with Node.js, and usually default to Node.