簡體   English   中英

如何從測試組件觸發 Ember 組件中的函數?

[英]How do I trigger a function in an Ember component from the test component?

在單元測試 ComponentA-test 中,我想觸發 ComponentA 中的函數 load(),但這樣做時遇到問題。

that I would have written in the component to trigger it.在下面的代碼示例中的 assert.equal 之前,我想向添加一些類似的東西,我會在組件中編寫它來觸發它。 但我似乎找不到這樣做的正確語法。

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

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

您可以在此處執行幾項操作,但這取決於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
});

Octane/Glimmer 組件的更新:我今天從 Ember 核心團隊成員的評論中了解到,他們“目前不支持 Glimmer 組件的單元測試”

在此評論中復制建議的解決方法,“讓您可以從渲染測試中訪問組件實例”

module('my-thing', function(hooks) {
  setupRenderingTest(hooks);

  test('something that wants to exercise an internal method', async function(assert) {
    let component;

    this.owner.register('component:my-thing', class extends MyThing {
       constructor(owner, args) {
         super(owner, args);
         component = this;
       }
    });
    
    await render(hbs`<MyThing />`);

    // now I can interact with `component` without issue
  });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM