我有一个初始化程序,该初始化程序从脚本标签页上的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