THA*_*iSi 14 javascript model-view-controller unit-testing ember.js
我们正在学习Ember.js.我们做所有开发TDD,并希望Ember.js也不例外.我们有构建Backbone.js应用程序测试驱动的经验,因此我们熟悉使用Jasmine或Mocha/Chai测试前端代码.
在确定如何测试视图时,当视图使用的模板具有#linkTo语句时,我们遇到了问题.遗憾的是,我们无法找到好的测试示例和实践.这个要点是我们寻求如何正确地对ember应用程序进行单元测试的答案.
当在寻找在Ember.js源代码测试linkTo,我们注意到它包含灰烬应用程序支持的完整线路#linkTo.这是否意味着我们在测试模板时不能存在这种行为?
如何使用模板渲染为ember视图创建测试?
这是我们的测试要点和将使测试通过的模板,以及使其失败的模板.
view_spec.js.coffee
# This test is made with Mocha / Chai,
# With the chai-jquery and chai-changes extensions
describe 'TodoItemsView', ->
beforeEach ->
testSerializer = DS.JSONSerializer.create
primaryKey: -> 'id'
TestAdapter = DS.Adapter.extend
serializer: testSerializer
TestStore = DS.Store.extend
revision: 11
adapter: TestAdapter.create()
TodoItem = DS.Model.extend
title: DS.attr('string')
store = TestStore.create()
@todoItem = store.createRecord TodoItem
title: 'Do something'
@controller = Em.ArrayController.create
content: []
@view = Em.View.create
templateName: 'working_template'
controller: @controller
@controller.pushObject @todoItem
afterEach ->
@view.destroy()
@controller.destroy()
@todoItem.destroy()
describe 'amount of todos', ->
beforeEach ->
# $('#konacha') is a div that gets cleaned between each test
Em.run => @view.appendTo '#konacha'
it 'is shown', ->
$('#konacha .todos-count').should.have.text '1 things to do'
it 'is livebound', ->
expect(=> $('#konacha .todos-count').text()).to.change.from('1 things to do').to('2 things to do').when =>
Em.run =>
extraTodoItem = store.createRecord TodoItem,
title: 'Moar todo'
@controller.pushObject extraTodoItem
Run Code Online (Sandbox Code Playgroud)
broken_template.handlebars
<div class="todos-count"><span class="todos">{{length}}</span> things to do</div>
{{#linkTo "index"}}Home{{/linkTo}}
Run Code Online (Sandbox Code Playgroud)
working_template.handlebars
<div class="todos-count"><span class="todos">{{length}}</span> things to do</div>
Run Code Online (Sandbox Code Playgroud)
我们的解决方案基本上是加载整个应用程序,但尽可能地隔离我们的测试主题.例如,
describe('FooView', function() {
beforeEach(function() {
this.foo = Ember.Object.create();
this.subject = App.FooView.create({ foo: this.foo });
this.subject.append();
});
afterEach(function() {
this.subject && this.subject.remove();
});
it("renders the foo's favoriteFood", function() {
this.foo.set('favoriteFood', 'ramen');
Em.run.sync();
expect( this.subject.$().text() ).toMatch( /ramen/ );
});
});
Run Code Online (Sandbox Code Playgroud)
也就是说,路由器和其他全局变量都是可用的,因此它不是完全隔离的,但我们可以轻松地发送双精度数据,以便更接近被测对象.
如果你真的想要隔离路由器,linkTo帮助器会查找它controller.router,所以你可以这样做
this.router = {
generate: jasmine.createSpy(...)
};
this.subject = App.FooView.create({
controller: { router: this.router },
foo: this.foo
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2392 次 |
| 最近记录: |