title: Triggering event on an element in memory when testing Backbone Views
body: <p>I am writing some integration tests for my Backbone views/models/collections. When I call <code>render</code> on my <code>View</code>, it simply renders a template to it's own <code>el</code> property, hence the html is simply stored in memory rather than on the page. Below is a simple model, and a view with a click event bound to a DOM element:</p>
  
  <pre><code>var model = Backbone.Model.extend({
      urlRoot: '/api/model'
  });
  
  var view = Backbone.View.extend({
      events: {
          'click #remove': 'remove'
      }
      render: function () {
          var html = _.template(this.template, this.model.toJSON());
          this.$el.html(html);
      },
      remove: function () {
          this.model.destroy();
      }
  });
  </code></pre>
  
  <p>I am using Jasmine to write my tests. In the test below all I want to do is spy on the <code>remove</code> function to see if it is called when the click event is fired for the element <code>#remove</code> which is present in the template I pass to the view.</p>
  
  <pre><code>// template
  
  &lt;script id="tmpl"&gt;
      &lt;input type="button" value="remove" id="remove"/&gt;
  &lt;/script&gt;
  
  // test
  
  describe('view', function () {
  
      var view;
  
      beforeEach(function () {
          view = new view({
              template: $('#tmpl').html(),
              model: new model()
          });
      });
  
      it('should call remove when #remove click event fired', function () {       
          view.$('#remove').click();
  
          var ajax = mostRecentAjaxRequest();
          expect(ajax.url).toBe('/api/model');
          expect(ajax.method).toBe('DELETE');
      });
  
  });
  </code></pre>
  
  <p>However, as the <code>#remove</code> element is in memory, and it hasn't actually been added to the DOM, I'm not sure how you would simulate the click event. In fact I'm not even sure if it's possible?</p>
  
  <p>It may seem a bit strange to want to do this in a test, but with my tests I am trying to test <strong>behaviour</strong> rather than <strong>implementation</strong>, and this way I don't care what is happening in between - I just want to test that if the user clicks <code>#remove</code> a <code>DELETE</code> request is sent back to the server.</p>