11

根据版本的博客文章,商店现在可以用作服务:ember-data1.0.0-beta.16

TweetComposerComponent = Ember.Component.extend({
  store: Ember.inject.service()      
});

但是,我不知道如何qunit对这样的组件进行单元测试。我尝试了以下方法:

moduleForComponent('tweet-composer', {
  needs: ['service:store']
});

和:

moduleForComponent('tweet-composer', {
  needs: ['store:main']
});

当我做前者时,我会得到一个错误Attempting to register an unknown factory: 'service:store',如果我做后者,那store就是undefined.

想法?

(我正在写一个ember-cli风格的应用程序)。

更新:

在 ember-test-helpers repo 中似乎有一个未解决的问题。

在等待此修复程序时,我制作了一个可以作为权宜之计的助手(coffeescript):

`import TestModuleForComponent from 'ember-test-helpers/test-module-for-component'`
`import { createModule } from 'ember-qunit/qunit-module'`

# This assumes the last argument, the callbacks, is present, although it
# does support the description being an optional argument.
moduleForStoreComponent = ->
  args = Array.prototype.slice.call arguments
  callbacks = args[args.length-1]
  # Wrap the original beforeEach callback in a modified version that
  # also sets up the store for the test container.
  originalSetup = callbacks.beforeEach
  callbacks.beforeEach = ->
    DS._setupContainer(@container)
    originalSetup.call(@) if originalSetup
  callbacks.store = ->
    @container.lookup('store:main')
  args.unshift TestModuleForComponent
  createModule.apply @, args

`export default moduleForStoreComponent`
4

1 回答 1

13

单元测试是除了您正在测试的代码/组件/单元之外,一切都可以完美运行的地方。

因此,甚至store应该假设它工作正常(0 个错误/错误)。

像这样的东西应该在你的测试中起作用:

moduleForComponent('tweet-composer', {
    beforeEach: function() {
        this.subject({
            store: {/*empty object*/}
        });
    }
});

如果您的部分测试依赖于从商店检索到的数据,您可以执行以下操作:

this.subject({
    store: {
        find: function() {
          var mockedModel = Ember.Object.create({/*empty*/});
          return mockedModel;
        }
    }
});

这是为了保留“单元测试”的状态,如果您开始从您的应用程序中包含和注册其他对象,那么您实际上是在编写集成测试。

笔记:

一般来说,直接在组件中查找模型是一种反模式,您应该更愿意在包含该组件的模板中传递您需要的任何模型。

http://discuss.emberjs.com/t/should-ember-components-load-data/4218/2?u=givanse

于 2015-04-20T23:54:19.173 回答