本文介绍了EmberJS:如何使用ember-qunit的moduleFor来测试控制器动作,它使用ember-data的存储的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想测试一个这样的控制器操作:

I want to test a controller action like this:

createNewBase: function () {

  var attributesForNewBase = this.get( 'model' ).getProperties( ... ),
      self = this,
      newBase = this.store.createRecord( ..., {

        ...

      } );

  newBase.save().then( function ( createdBase ) {

    self.send( 'setBaseOfModel', createdBase );

  }, function ( error ) {

    console.log( error );

  } );

}

问题是如果我使用ember-qunit的moduleFor测试这个动作,商店是未定义的。那么我要做什么或创建这样的测试的正确方法是什么?

The problem is that if I use moduleFor of ember-qunit to test this action the store is undefined. So what do I have to do or what is the correct way to create such tests?

推荐答案

你可以创建一个模拟商店。这样的东西:

You could create a mock store. Something like this:

controller.set('store', {
    createRecord: function() {
        return {
            save: function() {
                return Ember.RSVP.resolve();
            }
        };
    }
});

这将允许您的控制器的功能就好像商店真的在那里,而在同一时间,提醒您,如果控制器与您未提前计划的商店进行任何操作。

This will allow your controller to function as if the store was really there, while at the same time, alerting you if the controller does anything with the store that you didn't plan for ahead of time.

替代方案是实际设置您的商店进行测试,但是这更多涉及。如果你想这样做,写一个集成测试而不是单元测试可能会更容易。

The alternative would be to actually set up your store for testing, but that's slightly more involved. If you wanted to do that, it might be easier just to write an integration test instead of a unit test.

这篇关于EmberJS:如何使用ember-qunit的moduleFor来测试控制器动作,它使用ember-data的存储的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 23:47