0

我是 node.js 的新手,我正在尝试在一个项目中进行协作,为其添加 mocha 测试套件。我目前遇到的问题如下

ReferenceError: Board is not defined
at new Game (/Users/.../dr_mojo/public/javascripts/game.js:8:20)
at Context.<anonymous> (/Users/.../dr_mojo/test/test.game.js:13:17)
at Test.Runnable.run (/usr/local/lib/node_modules/mocha/lib/runnable.js:213:32)
at Runner.runTest (/usr/local/lib/node_modules/mocha/lib/runner.js:343:10)
at Runner.runTests.next (/usr/local/lib/node_modules/mocha/lib/runner.js:389:12)
. . .

当运行我的测试时

$> mocha -u tdd test/test.game.js --reporter spec

公共/javascripts/board.js

function Board(width, height) {
  this.board = new Array(width);
  this.width = width;
  this.height = height;
  for( var i = 0; i < width ; ++i) {
    this.board[i] = new Array(height);
  }
}
...
if(typeof module != 'undefined') {
  module.exports.Board = Board;
}

公共/javascripts/game.js

function Game(lvl, speed, music) {
  this.initial = { ... };
  this.board = new Board(board_size[0], board_size[1]);
  ...
}
...
if(typeof module != 'undefined') {
  module.exports.Game = Game;
}

测试/test.game.js

var assert = require("assert");
var Board  = require(__dirname + "/../public/javascripts/board.js").Board;
var Pill   = require(__dirname + "/../public/javascripts/pill.js").Pill;
var Game   = require(__dirname + "/../public/javascripts/game.js").Game;

describe('Game', function(){
  it('Clears a row', function(){
    var game  = new Game();
    var pill1 = new Pill(game.board, game.detector, [ {x : 0 , y : 0 }, {x : 1, y : 0 } ],["red", "red"]);
    var pill2 = new Pill(game.board, game.detector, [ {x : 2 , y : 0 }, {x : 3, y : 0 } ],["red", "red"]);

    assert.equal(game.board.matches().length, 1);

    game.findMatches(function(){});
    assert.equal(game.board.matches().length, 0);
  })
})

服务器.js

var express = require('express'),
    port    = 8888;

var app = express.createServer();

app.use(express.static(__dirname + '/public'));
app.set("view engine", "jade");
app.set('view options', { layout: false });

app.get('/play', function(req, res){
  res.render('play_game');
});

app.listen(port);

如您所见,错误game.js:8在于我不知道如何正确配置它,因为在玩游戏时它可以正常工作,这意味着可以new Game()正常工作,问题是我没有正确配置它从测试套件。我会很感激任何帮助。提前致谢。

4

1 回答 1

0

根据您提供的代码,我的猜测是您需要require从 game.js 到 board.js,如下所示:

var Board  = require(__dirname + "/../public/javascripts/board.js").Board;

看起来这是一款您也在 node.js 中测试的浏览器游戏。那是对的吗?

于 2012-12-19T20:01:17.367 回答