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)
Alternative
I can change all existing unit tests, by adding this line:
var expect = require('chai').expect;
and changing the syntax of the assert to
expect(sut).to.be.closeTo(5.00000, 0.00001);
This is a feasible alternative, since I only got a few dozens of tests. But I'm still interested in finding an answer to the question above.