Search code examples
javascriptjasminees6-classteaspoon

Calling a Javascript class method gets error 'Can't find variable'


When I run my teaspoon-jasmine test, I get the following error.

Error

ReferenceError: Can't find variable: modify_create_favorite in http://localhost:3000/assets/favorite.self-67fd17843e64bfbeed401bd.js?body=1?body=1 (line 49)

favorite.js file

class Favorites {

  static create(listing_id) {
    modify_create_favorite(find_favorite(listing_id));
  }

  static find_favorite(listing_id) {
    return $("#i-favorite-"+listing_id);
  }

  static modify_create_favorite(object) {
    object.removeClass('fa-heart-o').addClass('fa-heart').parent().attr('data-method','delete');
  }
}

teaspoon jasmine:

  it("will change the class", function() {
    fixture.set(favorite_html);
    Favorites.create('17');
    expect( $('#i-favorite-17', fixture.el) ).not.toHaveClass( 'fa-heart-o')
    expect( $('#i-favorite-17', fixture.el) ).toHaveClass( 'fa-heart')
    expect( $('#i-favorite-17', fixture.el).parent() ).toHaveAttr("data-method",'delete')    
    expect(jQuery).toBeDefined();
  });

Solution

  • static methods can only be invoked by calling the class without creating an instance, so inside create you should do:

    Favorites.modify_create_favorite(Favorite.find_favorite(listing_id))
    
    //or 
    this.modify_create_favorite(this.find_favorite(listing_id))
    

    In your current implementation your code is looking for a function called modify_create_favorite() because doesn't know that is a method of your class.

    More on static methods https://developer.mozilla.org/en-US/docs/Web/JavaScript/reference/Classes/static