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

标签 javascript unit-testing ember.js integration-testing

这是针对 Ember 2.2.0 的。我想使用来 self 的 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
  });
});

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

关于javascript - 如何在集成测试中访问 ember 数据存储实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34772491/

相关文章:

javascript - 使用 karma-jasmine 测试规范内的对象属性更改

jquery - 使用mockjax进行模拟rest API调用

javascript - 在 Javascript 中获取用户定义的对象

javascript - react-native-router-flux 警告 : Key is already defined

visual-studio-2010 - SQL Server 角色提供程序单元测试期间出现 "The role manager feature has not been enabled"错误

unit-testing - 单元测试 : TEST Fixture, 或 TEXT Fixture

javascript - 如何定位子菜单元素(xpath、className 或 css 定位器)

javascript - 如何在 contenteditable 元素中保持插入符号的位置

ember.js - 如何使用mailto href和bindAttr对属性设置 'a'标签?

node.js - 创建一个 Ember CLI in-app/in-repo Addon : how to install npm dependencies?