I'd like mock out MarkdownDeep, I've the following code, in JavaScript
MarkdownDeep = new (function () {
this.Markdown = function () {
this.Transform = function (a) {
return "html";
};
};
})();
but I'm having trouble implementing this in CoffeeScript
I tried the following
MarkdownDeep = new (->
@Markdown = ->
@Transform = (a) ->
"html"
)()
window.MarkdownDeep = MarkdownDeep
but it doesn't work, specifically in my unit test markdown = new MarkdownDeep.Markdown() gives "undefined is not a function", though the JS version mocks out fine.
Your example results in the following javascript code:
var MarkdownDeep;
MarkdownDeep = new (function() {
return this.Markdown = function() {
return this.Transform = function(a) {
return "html";
};
};
});
window.MarkdownDeep = MarkdownDeep;
The line return this.Markdown = function() { /* ... */ } makes the function the object returned by the new operator.
Writing
MarkdownDeep = new (->
@Markdown = ->
@Transform = (a) ->
"html"
return
return
)
window.MarkdownDeep = MarkdownDeep
fixes the problem.
Addition: This answer mentions the algorithm for object construction in javascript
CoffeeScript's implicit returns can lead to mayhem when used in conjunction with new. As others have pointed out, you could use explicit returns. Another option is to use class, which creates a function (the constructor) with no implicit return:
MarkdownDeep = new class
constructor: ->
@Markdown = class
constructor: ->
@Transform = (a) ->
'html'
Of course, that's not very readable in this case, but as a general rule, you'll save yourself headaches by using class whenever you use new.
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