如何从测试组件触发Ember组件中的功能?

时间:2019-08-14 16:55:15

标签: ember.js ember-qunit

在单元测试ComponentA测试中,我想在ComponentA中触发函数load(),但是这样做有问题。

在下面的代码示例中的assert.equal之前,我想向 this.load()添加类似的东西,这些东西我会在组件中编写以触发它。但是我似乎找不到合适的语法。

    test('should render some information', async function (assert)) {
       await render(hbs`{{componentA}}`);

       assert.euqal(".info").text().trim(), "info text");
    }

1 个答案:

答案 0 :(得分:1)

您可以在此处执行几项操作,但这取决于load是否为操作。可能还有其他测试方法,但这是我使用的最常用方法。

如果load是一项操作,并且是由DOM事件(例如,单击按钮)触发的,则可以通过在集成测试中执行该DOM事件来触发功能:

test('should render some information', async function(assert) {
  await render(hbs`{{componentA}}`);

  // if a button has the action modifier:
  // <button {{action "load"}}>Click me</button>
  // then you can do this in your test to trigger the action:

  await click('button');

  // assertions go here
});

如果它只是组件中的常规函数​​,并且您想在组件的实例上手动调用此函数,则可以在组件单元测试中尝试这样做。这里唯一的陷阱是您将不能断言任何DOM更改。

test('should do something', function(assert) {

  const component = this.owner.factoryFor('component:componentA').create();

  component.load();

  // assertions go here
});