Scott Weinstein Scott Weinstein - 4 months ago 8
CoffeeScript Question

How do I use CoffeeScript to mock out existing code?

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.

Answer

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

Comments