gpt4 book ai didi

ember.js - 如何使用 qunit 在 Ember 单元测试中依赖商店即服务?

转载 作者:行者123 更新时间:2023-12-04 02:01:56 24 4
gpt4 key购买 nike

根据 the blog-postember-data版本1.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'如果我做后者,那么 storeundefined .

想法?

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

更新:

似乎有一个 open issue为此在 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`

最佳答案

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

所以,即使是 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;
}
}
});

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

笔记:

In general, looking up models directly in a component is an anti-pattern, and you should prefer to pass in any model you need in the template that included the component.



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

关于ember.js - 如何使用 qunit 在 Ember 单元测试中依赖商店即服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29756882/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com