【问题标题】:How to mock readline.createInterface()?如何模拟 readline.createInterface()?
【发布时间】:2017-08-05 17:07:20
【问题描述】:

我正在尝试在 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();
  });
});

有人有什么建议吗?

【问题讨论】:

    标签: javascript testing jasmine mocking readline


    【解决方案1】:

    尝试以下代码(见上文)并使用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();
      });
    });

    【讨论】:

      【解决方案2】:

      当我尝试重新创建此问题时,我得到一个不同的错误:

      Expected spy readline.createInterface to have been called.
      

      但是,如果您只监视一个方法,请尝试使用 jasmine 的 spyOn 表示法:

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

      怀着同样的期待。对于这个用例,它比 jasmine.createSpyObj() 表示法更清晰,并且不使用任何额外的库。

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

      【讨论】:

        猜你喜欢
        • 2022-01-21
        • 2022-01-21
        • 2014-11-26
        • 1970-01-01
        • 1970-01-01
        • 2012-08-03
        • 2014-07-01
        • 1970-01-01
        相关资源
        最近更新 更多