Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unit test view bindings and templates on Emberjs?

Tags:

ember.js

bdd

I'm trying to TDD/BDD my way into ember and I was wondering how do you unit test template bindings or view bindings?

And what is the best practice to test your handlebars templates, if it should be tested at all..?

Thanks, Shai

like image 638
Shai Reznik - HiRez.io Avatar asked Jul 12 '12 16:07

Shai Reznik - HiRez.io


1 Answers

I didn't find anyone talking about this subject directly, so I wrote a post about my findings.

I also opened up a new open source project dedicated to unit testing emberjs apps called emberjs-tdd

Basically what I did is to use the View.$() function to test that my template elements are connected to my view, and for the bindings I used mock data injection and then compared my input value with the mock data.

Something like:

 describe("Given a login view it", function(){
    var loginView = null;

    beforeEach(function(){
        loginView = LoginView.create();

        Ember.run(function(){
            loginView.append();
        }); 
    });

    afterEach(function(){
        Ember.run(function(){
            loginView.remove();
        });
        loginView = null;
    });


    it("Should be defined", function(){
        expect(loginView).toBeDefined();
    });

    it ("Should have a user property", function(){
        expect(loginView.get("user")).toBeDefined();
    });

    describe("Should have a template and it", function(){

        it("Should have an user input", function(){
            expect(loginView.$("input.userInput").length).toEqual(1);
        });

        it("Should bind the username input value to the user.name property", function(){
            Ember.run(function(){
                loginView.set("user", Em.Object.create({name:"mockValue"}));
            });
            expect(loginView.$("input.userInput").val()).toEqual("mockValue");  
        });

        it("Should have a login button", function(){
            expect(loginView.$("button.loginButton").length).toEqual(1);
        });


    });

});

And my view code is:

define(["text!templates/LoginView.handlebars","ember"],function(LoginTemplate){
 var loginView = Em.View.extend({
    template: Em.Handlebars.compile(LoginTemplate),
    user: null
 });
 return loginView;
});

And my template:

{{view Ember.TextField class="userInput" valueBinding="user.name"}}
<button class="loginButton">Login</button>

Again, the full project can be found on the emberjs-tdd project, so please fill free to contribute your findings to this project so we'll have a better idea on how to do this stuff efficiently.

like image 155
Shai Reznik - HiRez.io Avatar answered Nov 07 '22 07:11

Shai Reznik - HiRez.io