-->

ReferenceError: CoffeeScript + JsTestDriver + Quni

2019-07-28 23:32发布

问题:

Currently I'm looking into TDD with CoffeeScript and JsTestDriver however I'm stuck on a ReferenceError thrown by JsTestDriver.

Some info:

  • Using the IntelliJ JsTestDriver plugin
  • Testing via Chrome
  • Configured JsTestDriver the same way as on: http://code.google.com/p/js-test-driver/wiki/QUnitAdapter
  • Writing the tests in CoffeeScript
  • CoffeeScript is compiled to javascript and put in the configured directories before the test is run

Config

server: http://Mark-PC:9876/capture

load:
  - js/lib/main/*.js
  - js/lib/test/sinon.js
  - js/lib/test/qunit.js
  - js/lib/test/equiv.js
  - js/lib/test/QUnitAdapter.js
  - js/coffee/main/controllers/*.js
  - js/coffee/main/models/*.js
  - js/coffee/test/controllers/*.js

Controller

class PortfolioController extends Backbone.Controller
    constructor: ->

    test: (a, b) ->
        return a + b

Test code

module("PortfolioController", {
    setup: -> @routeSpy = sinon.spy()
    teardown: -> window.location.hash = ""
})

test 'indexRoute', ->
    c = new PortfolioController
    equals c.test(1, 1), 2, "1 + 1 = 2"

Problem

JsTestDriver throws a error

ReferenceError: PortfolioController is not defined
ReferenceError: PortfolioController is not defined
    at Object. (http://mark-pc:9876/test/js/coffee/test/controllers/PortfolioController.test.js:12:5)
    at [object Object].test indexRoute (http://mark-pc:9876/test/js/lib/test/QUnitAdapter.js:40:15)

Tried:

  • Removing dependancies such as jQuery, BackBone, etc
  • Removed Qunit adapter and tried with jstestdriver asserts
  • Added a class inside the test itself, then it worked

Seems like some kinda exporting issue or prototype conflict?

回答1:

Sounds like you need to make PortfolioController a global, perhaps by adding

root = window ? global
root.PortfolioController = PortfolioController

the end of the file, or by simply replacing

class PortfolioController extends Backbone.Controller

with

class @PortfolioController extends Backbone.Controller

taking advantage of the fact that this is the global root in that context.

CoffeeScript never exports anything beyond a file's scope automatically; you have to do it explicitly. See my explanation for this behavior here.