【问题标题】:Ember.js Testing async action in controllerEmber.js 在控制器中测试异步操作
【发布时间】:2016-02-13 17:56:48
【问题描述】:

我有一个控制器,它调用一个方法来执行一些异步操作并返回一个承诺。

export default Ember.Controller.extend({

  _upload: function() {
    // return a promise
  },
  actions: {
    save: function(item) {
      this._upload(item).then(function(response) {
        // Handle success
      }, function(error) {
        // Handle error
      }
    }
  }
});

我想对Handle successHandle error 下的代码进行单元测试。 在我的单元测试中,我使用

模拟了_uploadMethod
controller.set("_upload", function() {
  return new Ember.RSVP.Promise(function(resolve) {
    resolve({name: "image1"});
  });
});

然后我调用操作并断言成功处理程序已完成工作

controller.send("save", "item");
assert.equal(controller.get("selected.item"), "item");

问题是断言失败,因为它在 promise 被解决并且成功处理程序中的所有内容完成之前运行。

在检查断言之前如何等待承诺解决?

【问题讨论】:

    标签: ember.js ember-cli


    【解决方案1】:

    如果您尝试这样做会怎样:

    controller.set("_upload", function() {
      const promise = new Ember.RSVP.Promise(function(resolve) {
        resolve({name: "image1"});
      });
    
      promise.then(() => Ember.run.next(() => {
        assert.equal(controller.get("selected.item"), "item");
      }));
    
      return promise;
    });
    
    controller.send("save", "item");
    

    有点hacky的方式,但它可能会工作。

    【讨论】:

      【解决方案2】:

      要测试异步方法,您可以使用测试助手waitUntil 等待方法的预期返回,如下面的代码。

       controller.send('changeStepAsyncActionExample');                                   
       await waitUntil(() => {                                                     
         return 'what you expect to the Promise resolve';                                
       }, { timeout: 4000, timeoutMessage: 'Your timeout message' });
      
       // If not timeout, the helper below will be executed
      
       assert.ok(true, 'The promise was executed correctly'); 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-12-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多