2015-11-08 80 views
1

我如何測試一個組件中調用的動作?如何測試一個動作在一個組件測試中被調用

觸發動作有多種方式,例如點擊按鈕。現在我想測試點擊該按鈕時調用的操作實際上是否被調用。像expect.functionName.to.be.called什麼的。

我有以下代碼

test('it closes the create dialog when close btn is clicked', function(assert) { 
    this.render(hbs`{{group-create cancelCreateAction="cancelAction"}}`) 

    this.$('button.btn--primary').click() 
    expect('myAction').to.be.called? 
}) 

,所以我只是想知道我能做些什麼呢?

回答

0

那麼你的行爲做了我們不知道的事情。但是這裏有一個小的測試,我寫了一些DOM元素和當前路線。沒有你告訴我們你的行爲是什麼,很難說。

click('.someSavingButton'); 

    andThen(function() { 
    assert.equal(currentRouteName(), 'index'); 
    assert.equal(find('.something-new-in-the-dom').length, 1, "New item in HTML"); 
+0

不能在燼2.1.0中做這樣的事情。你如何導入'click'和'andThen'功能? – user1952811

+0

從'qunit'導入{module,test}; 從'../helpers/start-app'導入startApp; –

+0

你仍然會爲'andThen'和'click'定義一個undefined。你從哪裏進口? – user1952811

0

我偶然發現了這個問題,同時尋找一種方式來測試泡了在集成測試(而不是封閉行爲 )行動。也許你已經找到了解決方案,但我會回答讓下一個人比​​我更早找到它。

測試動作是否被調用的慣用方式是編寫一個模擬函數並聲明它將被調用。 在您的例子 - 之前關閉行動 - 寫這種測試的方法如下:

test('it closes the create dialog when close btn is clicked', function(assert) { 
    // make sure our assertion is actually tested 
    assert.expect(1); 

    // bind the action in the current test 
    this.on('cancelAction', (actual) => { 
    let expected = { whatever: 'you have expected' }; 
    assert.deepEquals(actual, expected); 

    // or maybe just an assert.ok(true) - but I am not sure if this is "good" style 
    }); 

    this.render(hbs`{{group-create cancelCreateAction="cancelAction"}}`) 

    this.$('button.btn--primary').click() 
    expect('myAction').to.be.called? 
}); 

如今,隨着閉合動作模式,結合模擬功能的正確的方法是

// bind the action in the current test 
this.set('cancelAction', (actual) => { 
    let expected = { whatever: 'you have expected' }; 
    assert.deepEquals(actual, expected); 
}); 

this.render(hbs`{{group-create cancelCreateAction=(action cancelAction)}}`) 
相關問題