如何模拟readline.createInterface()?

obe*_*lus 1 javascript testing mocking readline jasmine

我正在尝试编写一个关于jasmine的测试以检查是否readline.createInterface()已调用,但我一直收到错误消息:TypeError: readline.createInterface is not a function

这是我在游戏课中的大致内容:

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

  rl.prompt();
  // ... and the rest ... 
}
Run Code Online (Sandbox Code Playgroud)

和我的测试:

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

    game.run();

    expect(readline.createInterface).toHaveBeenCalled();
  });
});
Run Code Online (Sandbox Code Playgroud)

有人有建议吗?

Ale*_*nko 5

尝试以下代码(见上文)并使用重新连接

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();
  });
});
Run Code Online (Sandbox Code Playgroud)