wendy0402
wendy0402

Reputation: 495

el in view is undefined in testing backbone

I would like to test my view from backbone view. but I got problem, I try to obtain the element of my view using this.$el, the result is empty. when I check the this.el the result is undefined

when I try to search it using $('#container') it is exist and when I run it, it also works. The tag is exist, here is my view code

define([
  'jquery',
  'underscore',
  'backbone',
  'text!templates/setting.html',
  'js/service/Config'

  ],function($, _, Backbone, settingTemplate, Config){
    var settingView = Backbone.View.extend({
      el: $("#container"),
      initialize: function(){
        _.bindAll(this, "render");
      },
      render: function(){
        data = {}
        var compiledTemplate = _.template(settingTemplate, data);
        this.$el.append(compiledTemplate);
        this.delegateEvents();
        DroneConfig.getAll(function(obj){
          $('input[name=url]').val(obj.url);
          $('input[name=repo]').val(obj.repo);
          $('input[name=hostname]').val(obj.hostname);
          $('textarea[name=api_key]').val(obj.api_key);
        });
      }
    });
    return settingView;
});

and here is my test code:

    define(['js/view/settingView','text!templates/setting.html'], function(SettingView, texts){
  describe("Setting View", function() {
    it('render successfully', function() {
      $('body').append(__html__['app/js/test/test.html']);
      $(document).ready(function(){
        var x = new SettingView();
        x.render();
        expect($('#setting').html()).to.not.be.empty;
      });
    });
  });
});

Do you get any idea why is this happening? I even try to add $(document).ready(function(){}). thanks

Upvotes: 3

Views: 401

Answers (1)

mu is too short
mu is too short

Reputation: 434685

Keep in mind that $('#container') is a function call so your code is equivalent to this:

var $el = $('#container');
var settingView = Backbone.View.extend({
  el: $el,
  //...
});

That means that your code will be looking for #container when your Backbone.View.extend is executed. Apparently there is no #container element when that happens so you end up with an undefined value for el when Backbone tries to un-jQuery-ify the el you've supplied.

The easiest solution is to leave the jQuery stuff to Backbone and just use a selector for el:

el: '#container'

Then Backbone will consult the DOM when it needs to build $el and you should have a #container by then.

Upvotes: 3

Related Questions