3

Question: Is it possible to manually declare a variable in CoffeeScript

I'm currently starting with unittesting for CoffeeScript, while going through a tutorial I came to a point where I had to use the before() and after() functions. While you can declare the variable in JavaScript where it has to be, you can't do this in CoffeeScript afaik. One (but not best practice) solution would be to add them to the window object (like this). The code I'm working with is from http://sinonjs.org/.

This is the code I'm testing with:

describe 'Fake server', ->
  before(() -> server = sinon.fakeServer.create())
  after(() -> server.restore())

  it "calls callback with deserialized data", () ->
    callback = sinon.spy()
    getTodos(42, callback)

  # This is part of the FakeXMLHttpRequest API
  server.requests[0].respond(
    200,
    { "Content-Type": "application/json" },
    JSON.stringify([{ id: 1, text: "Provide examples", done: true }])
  )

  assert(callback.calledOnce)

Compiled to JavaScript, the before and after functions looks like this:

before(function() {
  var server;
  return server = sinon.fakeServer.create();
});
after(function() {
  return server.restore();
});

So as you see, the variable server is declared within the before function and therefor can't be used outside of the wrong scope.

2
  • The server.requests[0] line should fail, since server isn't initialised at that point, no...!? Commented Jan 7, 2016 at 9:27
  • That's correct and i don't seem to gete it working, but that's a problem for later, the solution you mentioned works fine (on other code) with the same before, after structure. Exactly for this fail I need to initialise server before the before() function Commented Jan 7, 2016 at 10:36

1 Answer 1

5
server = undefined  # or null, or false
before -> server = ...
after -> server.restore

While in Javascript you can do var foo;, in CoffeeScript you need to assign something to create the variable. But since var foo; means the value of foo is undefined, just assign undefined to create the same effect.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this is what I was looking for. I did try the server = null before which wasn't working. But with this confimation I know it must be my code which is wrong.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.