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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With