使用{{link-to}}帮助程序进行组件测试Ember-CLI

时间:2014-11-22 09:55:52

标签: ember.js ember-cli ember-qunit

我认为有3个非常简单的测试。

1)检查组件渲染属性(Ember-CLI自动生成此属性)

2)点击导航到' user.index'路线(它是{{link-to}})

3)点击导航到&brands; brands.index'路线(它是{{link-to}})

我可以确认在浏览器中单击它们时可以访问路由,但是测试失败了。 ' brands.index'测试始终期待' users.index'尽管指出了'品牌 - 链接'点击。

非常感谢任何帮助!

测试如下:

import {
  moduleForComponent,
  test
  } from 'ember-qunit';

moduleForComponent('navigation-bar', 'NavigationBarComponent', {
  // specify the other units that are required for this test
  // needs: ['component:foo', 'helper:bar']
});

test('it renders', function () {
  expect(2);

  // creates the component instance
  var component = this.subject();
  equal(component._state, 'preRender');

  // appends the component to the page
  this.append();
  equal(component._state, 'inDOM');
});

test('it can navigate to users', function () {
  expect(3);

  var component = this.subject();
  equal(component._state, 'preRender');

  this.append();
  equal(component._state, 'inDOM');

  click('.users-link');

  andThen(function () {
    equal(currentRouteName(), 'users.index');
  });
});

test('it can navigate to brands', function () {
  expect(3);

  var component = this.subject();
  equal(component._state, 'preRender');

  this.append();
  equal(component._state, 'inDOM');

  click('.brands-link');

  andThen(function () {
    equal(currentRouteName(), 'brands.index');
  });
});

组件模板是:

<nav class="navbar navbar-default" role="navigation">
    <div class="container-fluid">
        <div class="navbar-header">
            <a class="navbar-brand" href="#">
                <!--<img alt="Brand" src="...">-->
            </a>
        </div>
        <ul class="nav navbar-nav">
          {{#link-to 'users' tagName='li' classNames='users-link'}}<a href="#">Users</a>{{/link-to}}
          {{#link-to 'brands' tagName='li' classNames='brands-link'}}<a href="#">Brands</a>{{/link-to}}
        </ul>
    </div>
</nav>

2 个答案:

答案 0 :(得分:2)

我相信这是因为当您使用moduleForComponent帮助程序时,您没有启动Ember应用程序。 link-to帮助程序需要路由器,除非应用程序实际已启动(即使用常规module帮助程序并在startApp()中调用beforeEach,否则该路由器将不存在或正确设置})。

我不确定这里的最佳解决方案......你可以对使用这个组件的路线进行正常的集成测试,但这看起来很尴尬。

答案 1 :(得分:0)

问题是您正在尝试在要进行单元测试的文件中进行集成测试。阅读:http://emberjs.com/guides/testing/

对于集成测试,您需要执行以下操作:

import Ember from 'ember';
import startApp from '../helpers/start-app';

var App, server;

module('My First Integration Test', {
  setup: function() {
    App = startApp();
  },
  teardown: function() {
    Ember.run(App, 'destroy');
    server.shutdown();
  }
});

test('test something', function() {
});

根据您的库的版本,代码需要调整。