Lamdas Everywhere
Lamdas Everywhere

Reputation: 1686

Fundamental Testing of an Ember Component

I'm having some trouble testing an Ember.Component... I'm pretty sure I must be missing something, but it doesn't seem to be live binding the values in the template?

Perhaps someone could shed some light on why the first test on this jsbin pastie passes, but the second fails?

http://jsbin.com/UNivugu/22/edit

This is the broken one, (but see the jsbin for explicits):

test('Outputs a different attribute value on the component, when set and present in the template', function() {
  Ember.run(function() {
    component.set('someAttr', 'a non-default value');
    var result = component.$().text().trim();
    equal(result, "a non-default value", "it should render the default value");
  });
});

and here's the Component:

var SomeComponent = Ember.Component.extend({
  template: Ember.Handlebars.compile('{{someAttr}}'),
  someAttr: 'default value'
});

Thanks heaps!

Upvotes: 3

Views: 204

Answers (1)

Kingpin2k
Kingpin2k

Reputation: 47367

Actually the problem is you're attempting to access the view before Ember's had a chance to re-render the view. This is all part of how the run loop works, (for a fun example by Alex Matchneer look here: https://machty.s3.amazonaws.com/ember-run-loop-visual/index.html). Essentially Ember is going to wait until the very end of all of your changes to actually render in the page (this is due to rendering being the most expensive process). So what's happening is you're setting the value, Ember has a new task to update everyone who's watching that property, and after everyone is updated, Ember will finally re-render the property on the page. This is super useful if you happen to change the property multiple times in a row, Ember figures it will just update based on the last property.

All that being said, you can just schedule a task after the page has rendered to then see if the property has updated.

test('Outputs a different attribute value on the component, when set and present in the template', function() {
  Ember.run(function() {
    component.set('someAttr', 'a non-default value');
    stop();
    Em.run.schedule('afterRender',function(){
      start();
      var result = component.$().text().trim();
      equal(result, "a non-default value", "it should render the default value");
    });
  });
});

http://jsbin.com/UNivugu/27/edit

Upvotes: 5

Related Questions