2017-10-04 9 views
0

私はES6クラスのメソッドを模擬したい。node.jsとmochaテストで定義されていないSinonスタブ

私はモデルのモジュールをインポートしています:

// models/index.js 
models.user = user; 

その後:

モデルで
// test.js 
const models = require(path.resolve('./models')); 

がindex.jsがあるとmodels.userを呼び出している間、それはユーザーフォルダにindex.jsにリダイレクトフォルダ私はindex.jsでユーザークラスを持っている: //モデル/ユーザー/ index.js

class User extends Model { 
    // simplified exists - it returns boolean or thows an error 
    static async exists(username) { 
    if (username) { 
     returns true 
    } else { 
     throw new Error('bad output'); 
    } 
    } 
} 

私はワンsinonスタブを使ってスタブに存在する(username)メソッド。

const sinon = require('sinon'); 
const models = require(path.resolve('./models')); 

describe.only('generateTokenBehavior()', function() { 
    it('should return 200 given valid username and password', function() { 
     ... 
     const stub = sinon.stub(); 
     stub(models.user.prototype, 'exists').callsFake(true); 
     ... 
    }); 

を、私はスタブを持つ行にエラーを取得しています:

私がやっている

TypeError: Cannot read property 'callsFake' of undefined 

このコードの何が問題になっているのですか?私は同様のスタックの質問でこの問題を研究していましたが、答えが見つかりませんでした。

答えて

1

ここでの問題は、sinon.stubの結果を呼び出すと()関数として未定義を返すということです。参考のため

const sinon = require('sinon'); 
const models = require(path.resolve('./models')); 

describe.only('generateTokenBehavior()', function() { 
    it('should return 200 given valid username and password', function() { 
     ... 
     const stub = sinon.stub(models.user.prototype, 'exists').callsFake(true); 
     ... 
    }); 

、ドキュメントはここにある: http://sinonjs.org/releases/v4.1.1/stubs/#properties

私はそれをあなたが行った方法を書くためにあなたを責めないでください - ドキュメントは少し誤解を招くです。

関連する問題