创建虚假路由以测试组件的链接

时间:2018-03-18 13:25:35

标签: ember.js

我有一个获取菜单项并渲染导航栏的组件。所以现在我正在编写集成测试,我想确保该组件呈现正确的链接和标签。首先,我添加了路由器初始化以使link-to显示href道具:

moduleForComponent('main-menu', 'Integration | Component | main menu', 
{
  integration: true,
  setup() {
    const router = getOwner(this).lookup('router:main');
    router.setupRouter();
  }
});

现在我想创建一些假路由来测试组件,并独立于应用程序路由器的设置。所以我尝试使用map函数:

moduleForComponent('main-menu', 'Integration | Component | main menu', {
  integration: true,
  setup() {
    const router = getOwner(this).lookup('router:main');
    router.map(function() {
      this.route('link1');
      this.route('link2');
    });
    router.setupRouter();
  }
});

我得到Promise rejected before "it renders": router.map is not a function。那么我应该如何为测试实施“虚假路线”呢?

1 个答案:

答案 0 :(得分:1)

好的,解决了这个问题。如果有人需要类似的东西,请按照以下方式进行:

import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';
import { getOwner } from '@ember/application';
import CustomRouter from 'app/lib/router';

moduleForComponent('main-menu', 'Integration | Component | main menu', {
  integration: true,
  setup() {
    const application = getOwner(this),
          Router = CustomRouter.extend()
    ;
    Router.map(function() {
      this.route('link1');
      this.route('link2');
    });
    application.register('router:main', Router.extend());
    application.lookup('router:main').setupRouter();
  }
});

test('some awesome tests', function(assert) {
  const menuItems = [
      {url: 'link1', label: 'link1', href: '/link1'},
      {url: 'link2', label: 'link2', href: '/link2'},
    ]
  ;
  this.set('items', menuItems);
  this.render(hbs`{{main-menu items=items}}`);
  // some cool tests that now can check href attributes of links
  // and don't depend on app's router setup
});