Anconia
Anconia

Reputation: 4028

Mocha - coffeescript syntax

I'm converting some Mocha tests from JS to coffeescript and having issues with the beforeEach function. Below is what I currently have, but the data variable isn't being recognized in the test cases. Any suggestions?

beforeEach ->
  data =
    name: "test name"
    to: "alice"
    from: "bob"
    object1: "foo"
    object2: "bar"

And here is the original:

beforeEach(function(){
  data = {
    name: "test name",
    to: "Alice",
    from: "Bob",
    object1: "foo",
    object2: "bar"
  }
});

Upvotes: 0

Views: 187

Answers (1)

mu is too short
mu is too short

Reputation: 434635

In your JavaScript version:

beforeEach(function(){
    data = { ... }
});

data is a global variable because it isn't explicitly scoped to the function using var data. In your CoffeeScript version:

beforeEach ->
  data = ...

data is a local variable inside the beforeEach callback function because that's how variables work in CoffeeScript:

Lexical Scoping and Variable Safety

The CoffeeScript compiler takes care to make sure that all of your variables are properly declared within lexical scope — you never need to write var yourself.

and your CoffeeScript ends up like this JavaScript:

beforeEach(function(){
    var data = { ... }
});

and data is hidden away where you can't see it.

One solution is to manually create data outside the beforeEach:

describe 'Whatever', ->
  data = null
  beforeEach ->
    data = ...

That will give you the same data inside and outside beforeEach and data should be what you're expecting inside each of your its.

Another option is to use an instance variable for data:

beforeEach ->
  @data = ...

and then look at @data inside your its.

I'd prefer the first version (manually scoping data with data = null) because you never know when you're going to accidentally overwrite someone else's instance variable.

Upvotes: 1

Related Questions