如何创建虚拟组件以用于Ember集成测试?

vuv7lop3  于 2022-10-20  发布在  其他
关注(0)|答案(2)|浏览(137)

我有一个组件some-container,它接受Map到其他ember组件的id散列。这就是它的使用方式:

{{modules/some-container
  pageKey="foo"
  widgetIdToComponent=(hash
    foo=(component "modules/dummy-component")
  )
}}

我正在为这个组件编写一个集成测试,我想让这个测试独立于其他组件。是否有方法在Ember集成测试文件中定义虚拟组件?

ioekq8ef

ioekq8ef1#

@Tyler Becks的现有答案适用于遗留的emberqunit,但对于原生qunit(自:2017年起:https://github.com/emberjs/rfcs/blob/master/text/0232-simplify-qunit-testing-api.md),您可能会想要这样的东西(已知至少与ember Octane(3.16+)一起使用):

import { test, module } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';
import { hbs } from 'ember-cli-htmlbars';

import { render } from '@ember/test-helpers';
import { setComponentTemplate } from '@ember/component';
import templateOnly from '@ember/component/template-only';
import Component from '@glimmer/component';

module('name of test suite', function(hooks) {
  setupRenderingTest(hooks);

  test('name of test', async function(assert) {
    class MyComponent extends Component {}
    setComponetTemplate(hbs`your template here`, MyComponent);
    this.owner.register('component:component-name', MyComponent);

    await render(hbs`<ComponentName />`);
  });

  // alternatively, things get a bit simpler if you're using
  // ember-source 3.25+
  test('name of test 2', async function(assert) {
    class MyComponent extends Component {}
    setComponetTemplate(hbs`your template here`, MyComponent);

    this.setProperties({ MyComponent });

    await render(hbs`<this.MyComponent />`);
  });

  // template-only components are even simpler still
  test('name of test 3', async function(assert) {
    this.setProperties({ 
      MyComponent: setComponetTemplate(
        hbs`your template here`, 
        templateOnly()
      );
    });

    await render(hbs`<this.MyComponent />`);
  });
});
lbsnaicq

lbsnaicq2#

想出来了!解决方案是使用this.register。请参阅以下内容:

moduleForComponent('some-container', 'Integration | Component | some-container', {
  integration: true,

  beforeEach() {
    this.register(
      'component:foo-div',
      Component.extend({
        layout: hbs`<div data-test-foo />`
      })
    );

    this.register(
      'component:bar-div',
      Component.extend({
        layout: hbs`<div data-test-bar />`
      })
    );

    this.component = hbs`
    {{modules/some-container
      pageKey="foo"
      widgetIdToComponent=(hash
        fooId=(component "foo-div")
        barId=(component "bar-div")
      )
    }}`;
  }
});

test('it renders foo div when only foo div is returned', function(assert) {
  this.render(this.component);

  assert.dom('[data-test-foo]').exists('foo div renders');
  assert.dom('[data-test-bar]').doesNotExist('foo div renders');
});

相关问题