单元测试组件

时间:2014-03-08 16:51:30

标签: unit-testing ember.js

我花了最近24小时试图围绕我的一个EmberJS组件构建单元测试。我正在使用qunit。我想测试整个组件(把手模板和所有组件)作为一个不同的单元。

我的组件如下所示:

App.MyAwesomeComponent = Ember.Component.extend({
  someAttribute: null
  someComputedValue: function() {
    this.get('someAttribute') + ' some extra piece of text ';
  }.property('someAttribute')
});

components / my-awesome-component.handlebars文件如下所示:

{{someComputedValue}}

......测试看起来像这样:

test("When passed a string after rendering, renders the computed value as its content", function() {
  component = App.MyAwesomeComponent.create({
    templateName: "components/my-awesome"
  });
  appendComponentToView();
  component.set('someAttribute', 'an exciting value');
  var result = view.$().text().trim();
  equal(result, "an exciting value some extra piece of text ", "contents are rendered with the new value in place");
});

问题是我不断收到各种错误,例如“'null'不是一个对象(评估'depth0 ['my-awesome']')等。

我正在为单元测试组件寻找某种黄金路径。我不想使用集成测试(希望显而易见的原因 - 它是一个组件,我不想在我的应用程序中构建一个虚拟页面,所以我可以从各个角度测试它。)

在单元测试方面,ember网站上的文档非常缺乏,而且我所有的网络搜索对于我认为单元测试组件的标准情况都没有用。

提前致谢! :)

儒略

1 个答案:

答案 0 :(得分:2)

我通过使用runloop来实现这一点。

test("When passed a string after rendering, renders the computed value as its content", function() {
  component = App.MyAwesomeComponent.create({
    layoutName: "components/my-awesome"
  });
  appendComponentToView();
  Ember.run(function() {
    component.set('someAttribute', 'an exciting value');
  });
  var result = view.$().text().trim();
  equal(result, "an exciting value some extra piece of text ", "contents are rendered with the new value in place");
});

它工作的原因是runloop强制内部的位来精确地评估代码中的那一点,以便绑定在var result = ... line执行时更新了模板。

希望能给别人带来一些痛苦。