Reputation: 20262
I am experimenting with different ways to code a Node.js module and tried this:
game.js
var board = require('./board'),
player = require('./player');
// setting module.exports to a function constructor so I can make instances of this node module from my test
var game = module.exports = function(){};
// dynamically add properties and set their default values
// I don't think I need to use any prototypes here right?
// And yes I realize I could use ES6 classes with an explicit constructor but that's a suggestion we can put on the side for now...
game.initialize = function(){
game.started = false;
game.status = 'not started';
game.board = board.create();
return game;
};
game.start = function(){
game.started = true
};
game-test.js
let chai = require('chai'),
should = chai.should(),
game = require('../src/game');
describe('Game - Initial State', () => {
var newGame;
beforeEach((done) => {
newGame = new game().initialize;
done();
});
it('should contain a new board to play on', () => {
should.exist(newGame.board);
});
...
I'm getting the error "Cannot read property 'board' of undefined"
If I remove the .initialize() I get an instance of game but then no properties. I'm not sure if this is even a good pattern but first would like to know what I'm doing wrong here. And then any additional suggestions I'm open to hearing.
Upvotes: 1
Views: 509
Reputation: 6478
Game.initialize
is a function.
In your test your are not calling the function, so your variable newGame
is just a ref to Game.initialize
instead of a Game
instance
// your line
newGame = new game().initialize;
// should be
newGame = new game().initialize();
Edit: Also, you may want to use this
instead of game
in your initialize()
function.
Upvotes: 4