如何在集成测试中访问 ember 数据存储实例?

How do you access an ember data store instance in an integration test?

这是针对 Ember 2.2.0 的。我想使用来自 API 服务器的实时数据测试我的组件,使用 ember-data 而不是来自测试助手、手动 AJAX 请求或来自 ember-cli-mirage 之类的工具的模拟数据。目前我的测试中只有这段代码:

import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';

moduleForComponent('checkbox-group', 'Integration | Component | checkbox group', {
  integration: true
});

test('it renders', function(assert) {
  this.render(hbs`{{checkbox-group}}`);
  assert.equal(this.$().text().trim(), '');
});

我想做的是这样的:

test('it renders', function(assert) {
  const store = getStoreFromSomewhere();
  const model = store.find('data').then(() => {
    this.render(hbs`{{checkbox-group data=model}}`);
    // Do testing on component with model from server
  });
});

问题是我不知道如何获取商店实例,另外我不知道ember如何进行异步测试。

这些文档没有帮助:/。有人可以告诉我如何获取商店实例吗?如果那不可能,请使用 ember-data?

进行此测试的另一种方法

我认为这更像是验收测试而不是集成测试。验收测试设置整个应用程序,以便您可以对其进行测试。

我相信在集成测试中你应该伪造模型,比如:

test('it renders', function(assert) {
  const modelValue = Ember.Object.create({
     prop1: value1,
     prop2: value2,
  });
  this.set('model', modelValue);
  this.render(hbs`{{checkbox-group data=model}}`);
  // Do testing on component with fake model
  });
});

话虽如此,而且我认为我要说的内容仅在 Ember 2.2 之前有效(在 Ember 2.3 中已弃用, 我相信)。您可以执行以下操作:

let store = this.container.lookup('service:store');

但是,如果您这样做...您将在使用商店时遇到错误。

"Assertion Failed: You have turned on testing mode, which disabled the run-loop's autorun. You will need to wrap any code with asynchronous side-effects in a run"

这意味着您需要将异步代码包装在 Ember.run

Ember.run(() => {
  let store = this.container.lookup('service:store');
  store.findAll('post').then((posts) => {
     //do stuff
  });
});

我的两分钱是,不要在集成测试中直接使用商店。

moduleForComponent 规范中,我认为规范的方法是这样的:

var store = Ember.getOwner(this).lookup("service:store");

相对于:

var store = this.container.lookup('service:store');

而且,您可以在 beforeEach:

中像这样模拟它
this.promise = new Ember.RSVP.Promise((resolve) => {
  var response  = anEmberObject; 
  resolve(response);
});

this.storeMock = Ember.Service.extend({
  save: ()=>{
    return this.promise;
  },
  reload: (query)=>{
    return this.promise;
  }
});


Ember.getOwner(this).register('service:store', this.storeMock);
Ember.getOwner(this).inject('component', 'store', 'service:store');