1

コントローラーの一部である 2 つの別個の関数を呼び出す、ember コントローラーで定義された単一のアクションがあります。アクションメソッドが正しい関数を呼び出したかどうかを確認するために、単体テストでこれらの関数をモックアウトしたいと思います。

私のコントローラーは次のようになります。

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

実際には、コントローラーは機能しますが、単体テストでは、functionA と functionB は両方とも未定義です。コンソールにログインしようとしましthisたが、functionA と functionB の場所が見つからないため、適切にモックできません。アクションの隣のオブジェクトの最上位にあると思っていましたが、適切に定義されたものしか見つかりませんでし_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()
4

2 に答える 2

2

単体テストでコントローラーの機能を置き換えるには、パラメーターをthis.subject()関数に渡すことができます。

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

サンプルの tiddleを見てください。

この方法は、注入されserviceたコントローラーを置き換える場合に特に役立ちます。

于 2017-01-03T09:02:31.587 に答える
1

あなたが扱っている対応するプロパティを紹介します, 私たちは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();
            }
         }
    }
});

nameまた、 を呼び出した後にプロパティ値をテストできますactionMethod

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');
});
于 2017-01-02T15:07:07.840 に答える