如何模拟readline.createInterface()?

时间:2017-08-05 17:07:20

标签: javascript testing jasmine mocking readline

我正在尝试编写一个关于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 ... 
}

和我的测试:

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

    game.run();

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

有人有建议吗?

2 个答案:

答案 0 :(得分: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();
  });
});




答案 1 :(得分:0)

当我尝试重新创建此问题时,我收到了另一个错误:

Expected spy readline.createInterface to have been called.

但如果您只是在监视一种方法,请尝试使用茉莉花的间谍记法:

spyOn(readline, 'createInterface').and.callThrough();

抱着同样的期望。它比此用例的jasmine.createSpyObj()表示法更清晰,并且不使用任何其他库。

来源:https://jasmine.github.io/2.0/introduction.html