我有一个初始化器,它从页面上的脚本标记中的JSON对象向应用程序注册一些模块。在应用程序中工作正常,但测试失败,因为它无法找到预期的模型。
initialzers/bootstrap-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
};
测试/初始化/bootstrap-payload-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
字段似乎不工作在这种情况下。或者有什么方法可以让初始化器更易于测试?
感谢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