2017-11-26 6 views
0

私はES6を使用しています。mocha & chaiを使用してテストを開始します。ES6インポートネスト関数 - mocha

私の現在のテストファイルのコードは次のとおりです。

const assert = require('chai').assert; 
var app = require('../../../../src/app/login/loginController').default; 


describe('login Controller tests', function(){ 
    it('no idea ', function(){ 
     let result = app(); 
     assert.equal(result, 'hello'); 
    }) 
}) 

と私のloginController.jsです:私は私のテストファイル内の変数に「チェックアウト」関数をインポートしたい

class LoginController { 

    checkout(){ 
     return 'hello'; 
    } 
} 
export default LoginController 

が、これまで私はクラスだけをインポートすることができました。

ありがとうございます、ありがとう!

+0

はあなただけ作成しないでくださいあなたのテストで '新しいLoginController()'インスタンスが生成され、そのインスタンスの関数が呼び出されますか? – Andy

+0

ええ、私はインスタンスは必要ありません、私は関数が必要です。インポートされた関数を変数に含めることは可能ですか? –

+0

[Javascriptの静的関数宣言と通常の関数宣言の違い?](https://stackoverflow.com/questions/45594196/difference-between-static-function-declaration-and-the-normal-function-宣言) – str

答えて

0

メソッドをクラスから直接インポートすることはできません。仲介者としてクラスを持たない関数をインポートする場合は、クラス外で関数を定義する必要があります。または、実際にcheckoutをインスタンスメソッドにすることを意味していた場合は、そのインスタンスをインスタンスメソッドで呼び出す必要があります。ここで

はあなた由来例ファイルです:

export class LoginController { 

    // Satic function 
    static moo() { 
     return "I'm mooing"; 
    } 

    // Instance method 
    checkout() { 
     return "hello"; 
    } 
} 

// A standalone function. 
export function something() { 
    return "This is something!"; 
} 

そして、あなたはあなたの質問に表示ファイルから適応のすべての機能を行使するテストファイル、:

const assert = require('chai').assert; 

// Short of using something to preprocess import statements during 
// testing... use destructuring. 
const { LoginController, something } = require('./loginController'); 

describe('login Controller tests', function(){ 
    it('checkout', function(){ 
     // It not make sense to call it without ``new``. 
     let result = new LoginController(); 
     // You get an instance method from an instance. 
     assert.equal(result.checkout(), 'hello'); 
    }); 

    it('moo', function(){ 
     // You get the static function from the class. 
     assert.equal(LoginController.moo(), 'I\'m mooing'); 
    }); 

    it('something', function(){ 
     // Something is exported directly by the module 
     assert.equal(something(), 'This is something!'); 
    }); 
}); 
関連する問題