需要模型的Ember测试初始化​​器

时间:2015-07-15 18:07:52

标签: javascript unit-testing ember.js ember-cli ember-qunit

我有一个初始化程序,它通过脚本标记中页面上的JSON对象向应用程序注册一些模块。在应用程序中工作正常,但测试失败,因为它找不到预期的模型。

initialzers /自举-payload.js

export function initialize(container, application) {
  var store = container.lookup('service:store'),
    payloadKeys = Object.keys(BOOTSTRAP_DATA);

  payloadKeys.forEach((key) => {
    var registryKey = `bootstrap-payload:${key}`,
        model;

    model = store.createRecord(key, BOOTSTRAP_DATA[key]);
    application.register(registryKey, model, {instantiate:false});
  });
}

export default {
  name: 'bootstrap-payload',
  after: 'ember-data',
  initialize: initialize
};

测试/初始化/自举净荷-test.js

import Ember from 'ember';
import { initialize } from '../../../initializers/bootstrap-payload';
import { module, test } from 'qunit';

var registry, application;

module('Unit | Initializer | bootstrap payload', {
  needs: ['model:channel'],

  beforeEach: function() {
    Ember.run(function() {
      application = Ember.Application.create();
      registry = application.registry;
      application.deferReadiness();
    });
  }
});

// Replace this with your real tests.
test('it works', function(assert) {
  initialize(registry, application);

  // you would normally confirm the results of the initializer here
  assert.ok(true);
});

tests / index.html包含一个示例BOOTSTRAP_DATA变量,其中包含一个期望在那里被称为channel的模型。运行ember test时出现以下错误。

at http://localhost:7357/assets/test-support.js:5604: No model was found for 'channel'

如何在这种情况下needs字段似乎无法注入此依赖关系。或者无论如何都要使初始化程序更易于测试。

1 个答案:

答案 0 :(得分:1)

此答案归功于https://github.com/taras

我们可以创建一个验收测试,断言已将属性正确地注入我们的容器中,而不是为此初始化程序创建单元测试。

import Ember from 'ember';
import { module, test } from 'qunit';
import startApp from 'test-models-in-initializer/tests/helpers/start-app';
import Channel from 'test-models-in-initializer/models/channel';

var application;

module('Acceptance | index', {
  beforeEach: function() {
    window.BOOTSTRAP_DATA = {
      'channel': {
        'id': 0,
        'name': 'Test Channel',
        'internalName': 'test-channel',
        'logoUrl': '//somecdn.net/test-channel/logo.png'
      }
    };
    application = startApp();
  },

  afterEach: function() {
    Ember.run(application, 'destroy');
  }
});

test('channel type', function(assert) {
  let channel = application.registry.lookup('bootstrap-payload:channel');
  assert.ok(channel, "is registered");
  assert.ok(channel instanceof Channel);
});

在此处测试申请https://github.com/embersherpa/test-models-in-initializer