【问题标题】:Unit Testing Components单元测试组件
【发布时间】:2014-03-08 16:51:30
【问题描述】:

在过去的 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 网站上的文档在单元测试方面严重缺乏,而且我所有的网络搜索都对我看来是单元测试组件的标准案例毫无用处。

提前致谢! :)

朱利安

【问题讨论】:

  • components/my-awesome-component.handlebars 实际注入了名为components/my-awesome 的模板还是以components/my-awesome-component 的形式注入?
  • 我不知道。不知道我怎么知道。这与您刚刚回答的问题类似...我无法弄清楚如何使用模板简单地测试组件(我原本不知道您必须指定模板并且测试环境没有自动- 像普通的非测试余烬一样把它粘在一起)。
  • 我可能可以直接关闭这个问题,但它仍然提出了一个问题,即他们几乎没有记录如何在 ember 站点上进行单元测试的黄金路径。当我真的不再需要回答问题时,不确定该怎么办?
  • 好主意。现在可以了。

标签: unit-testing ember.js


【解决方案1】:

我通过使用 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");
});

它起作用的原因是运行循环强制内部位在代码中的那个点精确计算,以便绑定在 var result = ... 行执行时更新了模板。

希望能帮别人省一些痛苦。

【讨论】:

    猜你喜欢
    • 2018-03-04
    • 2019-04-18
    • 2011-10-23
    • 2016-10-19
    • 2023-03-15
    • 1970-01-01
    • 2016-07-09
    • 2021-01-05
    • 1970-01-01
    相关资源
    最近更新 更多