【问题标题】:Use rewire with Jest, to spy on console.log used in a private function对 Jest 使用 rewire,以监视私有函数中使用的 console.log
【发布时间】:2019-01-29 09:05:23
【问题描述】:

我在一个文件中有一个私有函数,它使用console.log。我想在我的Jest 测试中检查console.log 是否确实运行。因此要访问私有函数,我使用rewire

我有以下文件:

// a.js
function b() {
  console.log('c');
}

我有以下测试文件,其中我使用方法suggested hereconsole.log 替换为Jest 模拟函数,并使用method here 确保在rewire 之前进行替换:

// a.test.js
global.console = {
  log: jest.fn(),
};

const rewire = require('rewire');
const a = rewire('./a');

test('b', () => {
  a.__get__('b')();
  expect(global.console.log).toHaveBeenCalled();
});

然而,当我运行测试时,我得到:

  ● Test suite failed to run

    logger must implement log, warn and error methods

如果我改用以下测试代码:

// a.test.js
const rewire = require('rewire');
const a = rewire('./a');

a.__set__('console', {
  log: jest.fn(),
});

test('b', () => {
  a.__get__('b')();
  expect(global.console.log).toHaveBeenCalled();
});

我收到以下错误:

    expect(jest.fn())[.not].toHaveBeenCalled()

jest.fn() value must be a mock function or spy.
Received:
  function: [Function bound log]

在私有函数中使用 console.log 时,有什么办法可以窥探到吗?

【问题讨论】:

    标签: javascript module jestjs private console.log


    【解决方案1】:

    跟踪您给__set__ 的模拟并直接对其进行断言:

    const rewire = require('rewire');
    const a = rewire('./a');
    
    const logMock = jest.fn(
      (...args) => console.log('logMock called with', ...args)
    );
    
    a.__set__('console', {
      log: logMock,
    });
    
    test('b', () => {
      a.__get__('b')();
      expect(logMock).toHaveBeenCalled();
    });
    

    【讨论】:

    • 啊,是的,谢谢,效果很好!我相信这种技术对于用其他方法做同样的事情也很有用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-16
    • 2019-06-12
    • 2012-03-19
    • 2021-04-12
    • 2020-03-31
    • 2019-07-27
    相关资源
    最近更新 更多