I've recently started using jasmine to do javascript unit testing. loving it so far.
one of the projects i'm working on is a plugin for backbone.js. since backbone is an mvc style framework for javascript, a lot of what it does is view manipulation – typically through jquery. my plugin is no exception to this. i have several things being manipulated in html elements, through backbone views.
right now, i am doing what might be some awful stuff to make this worth with jasmine. here's an example of how i'm laying out my tests:
describe("conventionBindings", function(){
beforeEach(function(){
this.model = new AModel({name: "Some Name"});
this.view = new AView({model: this.model});
this.view.render();
});
afterEach(function(){
this.view.close();
});
describe("... that thing it does ... ", function(){
it("... stuff .... ", function(){
});
});
});
The important bits here, are the beforeEach and afterEach. notice that i'm calling my view's render method, and then my view's close method.
here's what those methods do:
AView = Backbone.View.extend({
render: function(){
this.html = $("");
$("body").append(this.html);
},
close: function(){
this.html.remove();
}
});
i'm specifically adding this "close" method to my view for the tests, because if i don't, then the jasmine page that i'm viewing when i run the jasmine test server would show the inputs that i've appended to the body of the page.
so… here's my questions:
is this a horrible thing to be doing? should i be testing my views and html element manipulations in some way other than appending elements to the body of the page?
right now i don't have a need to run these tests in any kind of CI server, but if i do, what kind of problems will i run into? how can i write better jasmine tests, so that i can test my backbone plugin in a CI server, knowing that the plugin has to manipulate html elements during the test?
Best Answer
I found this article a great resource for getting started with testing jasmine.
Testing Backbone applications with Jasmine and Sinon
In his write-up he's specifically appending elements to the page using setFixtures. So a similar method and it's the way I've used in the past. As far as best practice we might want to see how others feel about this method. I can't think of another way to perform the rendering without putting it on the page.