我正在尝试不同的方法来编写Node.js模块,并尝试了这个:
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
};
游戏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);
});
...
我收到错误"Cannot read property 'board' of undefined"
如果我删除了.initialize(),我会得到一个游戏实例,但之后没有属性。我不确定这是不是一个好的模式,但首先想知道我在这里做错了什么。然后我可以听到任何其他建议。
答案 0 :(得分:4)
Game.initialize
是一个功能。
在您的测试中,您没有调用该函数,因此您的变量newGame
只是Game.initialize
而不是Game
实例的参考
// your line
newGame = new game().initialize;
// should be
newGame = new game().initialize();
修改:此外,您可能希望在this
功能中使用game
代替initialize()
。