2017-01-02 50 views
1

我有一個單獨的動作定義在一個餘燼控制器調用2個獨立的功能,是控制器的一部分。我想在單元測試中嘲笑這些函數,以確認動作方法是否被稱爲正確的函數。如何單元測試一個餘燼控制器

我的控制器看起來是這樣的:

export default Ember.Controller.extend({ 
    functionA() { 
     return; 
    }, 
    functionB() { 
     return; 
    }, 
    actions: { 
     actionMethod(param) { 
      if(param) { 
       return this.functionA(); 
      } 
      else { 
       return this.functionB(); 
      } 
     } 
    } 
}); 

在實踐中,控制器的工作原理,但在單元測試,泛函和functionB都是不確定的。我試圖將this登錄到控制檯,但無法找到函數A和函數B的位置,所以我無法正確地模擬它們。我期望他們在動作旁邊的對象的頂層,但我只找到_actionsactionMethod正確定義。

我的單元測試看起來像下面

const functionA = function() { return; } 
const functionB = function() { return; } 
test('it can do something', function(assert) { 
    let controller = this.subject(); 
    // I don't want the real functions to run 
    controller.set('functionA', functionA); 
    controller.set('functionB', functionB); 
    controller.send('actionMethod', ''); 
    // raises TypeError: this.functionA is not a function 

    // this doesn't work etiher 
    // controller.functionB = functionB; 
    // controller.functionA = functionA; 
    // controller.actions.actionMethod(); 
} 

有沒有人對我怎樣才能在測試環境中代替那些功能的任何想法?或者,有沒有更好的方法來測試這個功能或設置我的控制器?

  • 編輯 錯字:this.subject到this.subject()
+0

側注:1.要創建控制器對象,你需要調用'this.subject()'。 2.'controller.send'方法不會返回任何值給調用者 – kumkanillam

+0

吶喊錯字 - 我叫'this.subject()'。至於'controller.send',我嘗試瞭如上所示的方法以及調用'controller.actions.actionMethod()' – user2989731

回答

1

要更換單元測試控制器的功能,可以傳遞參數到this.subject()功能:

let controller = this.subject({ 
    functionA(){ 
     //this function overriddes functionA 
    }, 
    functionB(){ 
     //this function overriddes functionB 
    }, 
}); 

the sample twiddle

該方法對於替換控制器的注入的service特別有用。

0

介紹與您正在處理性能,讓我們說name財產, 所以你的控制器就可以這樣看,

import Ember from 'ember'; 
export default Ember.Controller.extend({ 
    name:'', 
    functionA() { 
     this.set('name','A'); 
    }, 
    functionB() { 
     this.set('name','B'); 
    }, 
    actions: { 
     actionMethod(param) { 
      if(param) { 
       return this.functionA(); 
      } 
      else { 
       return this.functionB(); 
      } 
     } 
    } 
}); 

您可以在致電actionMethod後測試name屬性值。

test(" testing functionA has been called or not", function(assert){ 
    let controller = this.subject(); 
    controller.send('actionMethod',true); 
    //If you would like to call functionA just say controller.functionA() 
    assert.strictEqual(controller.get('name'),'A',' name property has A if actionMethod arguments true'); 
    controller.send('actionMethod',false); 
    assert.strictEqual(controller.get('name'),'B',' name property has B actionMethod arguments false'); 
}); 
+0

我只是試圖回答你的問題來學習我自己,坦率地說,我沒有寫過我的項目中的任何測試 – kumkanillam

+0

如果您想在創建對象時動態定義屬性,那麼您需要將它作爲參數傳遞給'subject'方法,就像我們在使用'create()'創建對象時所做的一樣。 'this.subject({functionA:function(){this.set('name','AA'); return;}});'' – kumkanillam