Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 928
Scott Weinstein Avatar asked Jun 20 '26 16:06

Scott Weinstein


2 Answers

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

like image 99
don_jones Avatar answered Jun 26 '26 11:06

don_jones


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.

like image 32
Trevor Burnham Avatar answered Jun 26 '26 10:06

Trevor Burnham



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!