5

如何在 Ember 中测试此代码?一般来说,请解释一下这个概念。

// app/routes/products/new.js
import Ember from 'ember';

export default Ember.Route.extend({
  model() {
    return this.store.createRecord('product');
  },
  actions: {
    willTransition() {
      this._super(...arguments);
      this.get('controller.model').rollbackAttributes();
    }
  }
});

我不知道怎么做。可能是路径中的存根模型?我发现商店在路线测试中不可用。

在 Ruby 和 RSpec 之后,所有这些新的 javascript 世界都有些混乱)但我还是想学习它。

4

1 回答 1

4

在单元测试中,想法是存根所有外部依赖项。在 ember 中,您可以这样做:

// tests/unit/products/new/route-test.js
test('it should rollback changes on transition', function(assert) {
  assert.expect(1);
  let route = this.subject({
    controller: Ember.Object.create({
      model: Ember.Object.create({
        rollbackAttributes() {
          assert.ok(true, 'should call rollbackAttributes on a model');
        }
      })
    })
  });
  route.actions.willTransition.call(route);
});

基本上,您将存根控制器和模型传递给this.subject(),然后调用您正在测试的任何函数(在这种情况下,您必须使用 call 或 apply 来调用具有正确范围的操作),然后断言rollbackAttributes()被调用。

assert.expect(1);在测试开始时告诉 QUnit 恰好等待 1 个断言。

于 2016-12-14T12:31:22.940 回答