2017-08-05 115 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(); 
 
    }); 
 
});