Monday 5 June 2017

Testing with node, mocha and chai (should/bdd syntax)

Context:

I'm a JavaScript hobbyist, and to take my project to the next level, I'm trying to setup a pipeline in BitBucket that will run my unit tests (and do other things later on).

I already used Mocha and Chai for testing, but I used it in the browser using an html page that sets up the dependencies and runs the tests.

Problem

The problem I'm facing is that I can't get the should syntax to work in node, while I did have working tests before in the browser. should should be available as part of the Chai library.

I initialized a new project with minimal code in it, but here it also doesn't work: should simply is not assigned.

package.json, including mocha and chai, and setting up mocha for testing.

{
  "name": "testtest",
  "version": "1.0.0",
  "description": "Minimal, complete and verifiable example",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "chai": "^4.0.1",
    "mocha": "^3.4.2"
  },
  "scripts": {
    "test": "mocha -u bdd"
  },
  "author": "GolezTrol",
  "license": "ISC"
}

test/test-foo.js, containing the test. The only thing I added is the first line with require. Before, the browser included the file and Foo was global. I echoed sut, giving me 5 and sut.should giving me undefined.

var Foo = require('../src/foo.js').Foo;

describe('Foo', function(){
  it('should flurp gnip snop', function() {
    var sut = Foo.flurp();
    console.log(sut); // 5
    console.log(sut.should); // undefined
    sut.should.be.closeTo(5.00000, 0.00001);
  });
});

src/foo.js, the actual unit being tested. In the old setup, Foo would be global (or actually add itself as a property to another global, but that's irrelevant now). I changed this, so it is exported as exports.Foo, so I can require it. This basically works, because I do get '5' in the test.

exports.Foo = function(){}; // Export Foo

var Foo = exports.Foo;

// Give Foo a method
Foo.flurp = function(){
  return 5;
}

The output I get from the test shows 'Foo' (the describe), 5 (the logged result) and undefined (the logged value of sut.should). After that, it obviously shows the formal output that the test has failed:

  Foo
5
undefined

<clipped for brevity>

  1) Foo should flurp gnip snop:
     TypeError: Cannot read property 'be' of undefined
      at Context.<anonymous> (test\test-foo.js:9:15)



via GolezTrol

No comments:

Post a Comment