在CoffeeScript文件上运行Jasmine测试时,对象未定义错误

object is not defined error when running Jasmine tests on CoffeeScript files

本文关键字:对象 未定义 错误 测试 Jasmine CoffeeScript 文件 运行      更新时间:2023-09-26

我一直在学习coffeescript,为了练习它,我决定学习TDD Conway的《生命的游戏》。我选择的第一个测试是创建一个细胞,看看它是死是活。为此,我创建了以下咖啡脚本:

class Cell 
  @isAlive = false

  constructor: (isAlive) ->
    @isAlive = isAlive
  
  die: ->
    @isAlive = false

然后,我使用以下代码创建了一个Jasmine测试文件(这是一个故意失败的测试):

Cell = require '../conway'
describe 'conway', ->
  alive = Cell.isAlive
  cell = null
  beforeEach ->
    cell = new Cell()
 describe '#die', ->
   it 'kills cell', ->
     expect(cell.isAlive).toBeTruthy()

然而,当我在Jasmine中运行测试时,我得到了以下错误:

cell is not defined

堆栈跟踪:

1) kills cell
   Message:
     ReferenceError: cell is not defined
   Stacktrace:
     ReferenceError: cell is not defined
    at null.<anonymous> (/Users/gjstocker/cscript/spec/Conway.spec.coffee:17:21)
    at jasmine.Block.execute (/usr/local/lib/node_modules/jasmine-node/lib/jasmine-node/jasmine-2.0.0.rc1.js:1001:15)
  

当我执行coffee -c ./spec/Conway.spec.coffee并查看生成的JavaScript文件时,我看到以下内容(第17行,第21列为错误):

// Generated by CoffeeScript 1.3.3
(function() {
  var Cell;
  Cell = require('../conway');
  describe('conway', function() {
    var alive, cell;
    alive = Cell.isAlive;
    cell = null;
    return beforeEach(function() {
      return cell = new Cell();
    });
  });
  describe('#die', function() {
    return it('kills cell', function() {
      return expect(cell.isAlive).toBeTruthy(); //Error
    });
  });
}).call(this);

我的问题是,据我所知,cell定义的。我知道我错了(从SELECT is not broken开始),但我正在努力弄清楚我哪里搞砸了。我如何用coffescapet诊断这个错误,并找出我错在哪里?

我研究了许多coffeescript应用程序中包含的源代码,包括这一个,但源代码的格式完全相同,声明也相同。

这是一个缩进问题,下面是您的解决方案:

Cell = require '../conway'
describe 'conway', ->
  alive = Cell.isAlive
  cell = null
  beforeEach ->
    cell = new Cell()
  describe '#die', ->
    it 'kills cell', ->
      expect(cell.isAlive).toBeTruthy()

如果你看一下编译后的JavaScript,你有一个describe块,里面有一个beforeEach。但你的下一个describe块(你想让在第一个块里面)实际上是而不是——它在外面。

这是因为第二个describe上的缩进只有一个空格,而不是两个空格。