2015-11-29 28 views
1

由於Node.js爲所需模塊創建全局單例,我如何在每個測試中創建下面我的遊戲的獨特實例?我想確保每次開始遊戲時,它都是從一個新的遊戲對象開始的,它將開始初始化爲false。在每次測試中爲所需模式模塊創建新對象

現在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; 
}; 

回答

2

如果你需要在每個測試實例化一個新的實例,那麼你需要定義gameboard爲一類。

然後,您可以在每個測試用例之前執行的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); 
    }); 
}); 
+0

我在之前做的是通過這樣做是爲了克隆它:JSON.parse(JSON。字符串化(遊戲));遊戲是必需的模塊。這對我有用,但是在尋找替代品,任何人告訴我,如果這對我來說是安全或正常的。 – PositiveGuy

+0

是啊所以你基本上改變這個不再使用節點模塊,但新的ES6類與出口? – PositiveGuy

+0

有趣我沒有必要添加完成()和我的測試運行綠色和失敗時,他們也應該。 – PositiveGuy

相關問題