在 Ember.RSVP.hash 中使用过滤器无法在 qunit test 中检索数据

Using filter inside Ember.RSVP.hash fails to retrieve data in qunit test

本文关键字:qunit test 数据 检索 Ember RSVP hash 过滤器      更新时间:2023-09-26

我在使用两个模型的路由上进行 qunit 测试,并使用Ember.RSVP.hash来完成此操作。事情按预期工作,但一旦我添加一个filterEmber.RSVP.hash它就会停止在 qunit 中检索数据。在 qunit 之外,它仍然可以工作,所以我相信这是filterEmber.RSVP.hashqunit的问题。

这是我的测试:

module('Ember.js Library', {
  setup: function() {
    Ember.run(App, App.advanceReadiness);
  },
  teardown: function() {
    App.reset();
  }
});
test('foo', function() {
  visit('/books');
  andThen(function() {
    equal(currentRouteName(), 'books.index');
  });
});

这是不使用filter的工作路线:

App.BooksRoute = Ember.Route.extend({
  model: function() {
    var id = 1;
    // note this does not filter "books" properly
    return Ember.RSVP.hash({
      books: this.store.find('books'),
      library: this.store.find('library', id)
    });
  }
});

以下是使用 filter 且不起作用的版本:

App.BooksRoute = Ember.Route.extend({
  model: function() {
    var id = 1;
    // note: filters "books" properly but doesn't work in qunit
    return Ember.RSVP.hash({
      books: this.store.filter('books', function(record) {
        return record.get('libraryId') === id;
      }),
      library: this.store.find('library', id)
    });
  }
});

最终结果是,在工作版本中,books按预期存在。在第二个版本中,books最终为空。在这两个版本中,library始终存在,因此我认为filter问题所在。

如何使用filter并让事情与 qunit 一起使用?

store.filter实际上并不加载记录,它只会返回存储中已有的记录。您可能想做的是类似...

App.BooksRoute = Ember.Route.extend({
  model: function() {
    var id = 1;
    // note: filters "books" properly but doesn't work in qunit
    return Ember.RSVP.hash({
      books: this.store.find('books').then(function(books){
        return books.filterBy('libraryId', id)
      }),
      library: this.store.find('library', id)
    });
  }
});

(免责声明:上面的代码未经测试,但就是这个想法)