首页 > 解决方案 > 如何从测试组件触发 Ember 组件中的函数?

问题描述

在单元测试 ComponentA-test 中,我想触发 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");
    }

标签: ember.jsember-qunit

解决方案


你可以在这里做几件事,但这取决于是否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
});

推荐阅读