2017-10-04 134 views
0

我想模擬一個ES6類的方法。Sinon存根未定義node.js和摩卡測試

我進口車型模塊:

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

在模型文件夾中有一個index.js並同時呼籲models.user並重定向到用戶文件夾index.js:

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

然後我在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'); 
    } 
    } 
} 

餘萬t用ston stub存根(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()作爲函數返回undefined

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

我不怪你寫它,你做的方式 - 文檔是有點誤導。