2017-08-05 186 views
1

我試圖寫在茉莉花的測試,以檢查readline.createInterface()叫,但我不斷收到一個錯誤,指出:TypeError: readline.createInterface is not a function如何模擬readline.createInterface()?

這裏大概是我有一個遊戲類:

run() { 
    let rl = readline.createInterface({ 
     input: process.stdin, 
     output: process.stdout, 
     prompt: 'OHAI> ' 
    }); 

    rl.prompt(); 
    // ... and the rest ... 
} 

和我的測試:

describe('run',() => { 
    it('should create readline interface',() => { 
    let readline = jasmine.createSpyObj('readline', ['createInterface']); 

    game.run(); 

    expect(readline.createInterface).toHaveBeenCalled(); 
    }); 
}); 

任何人有一個建議?

回答

5

嘗試下面的代碼(見上文),並使用rewire

const rewire = require('rewire') 
 
const game = rewire('path/to/game') 
 

 
describe('run',() => { 
 
    it('should create readline interface',() => { 
 
    const readline = jasmine.createSpyObj('readline', ['createInterface']); 
 
    const revert = game.__set__('readline', readline); 
 

 
    game.run(); 
 

 
    expect(readline.createInterface).toHaveBeenCalled(); 
 

 
    revert(); 
 
    }); 
 
});