由于Node.js为所需模块创建了一个全局单例,我如何在每个测试中创建下面的游戏的唯一实例?我想确保每次开始游戏时都会从一个新的游戏对象开始,该对象将初始化初始化为假。
现在game.start,游戏是每个测试中使用的相同的单身人士,我不希望这样,我不应该通过每次测试分享那个单身人士,这显然很糟糕。
let chai = require('chai'),
should = chai.should(),
game = require('../src/game');
describe('Starting the Game', () => {
it('should be able to start the game', () => {
game.start();
game.started.should.be.true;
});
it('should contain a new board to play on when game starts', () => {
game.start();
game.started.should.be.true;
should.exist(game.board);
});
});
game.js
var board = require('./board'),
player = require('./player');
var game = module.exports = {
start: start,
started: false,
board: board.create()
};
function start(){
game.started = true;
};
答案 0 :(得分:2)
如果您需要在每个测试中实例化一个新实例,那么您需要将game
和board
定义为一个类。
然后,您可以在beforeEach
方法中实例化新的游戏实例,并在每个测试用例之前执行。
<强> Game.js 强>
var Board = require('./board'),
Player = require('./player');
class Game {
constructor() {
this.started = false;
this.board = new Board();
}
start() {
this.started = true;
}
}
export default Game;
<强>游戏单元-test.js 强>
const chai = require('chai'),
should = chai.should(),
Game = require('../../test');
let game;
describe.only('Starting the Game', () => {
beforeEach((done) => {
game = new Game();
done();
});
it('should be able to start the game', () => {
game.start();
game.started.should.be.true;
});
it('should contain a new board to play on when game starts', () => {
game.start();
game.started.should.be.true;
should.exist(game.board);
});
});