代码之家  ›  专栏  ›  技术社区  ›  Gary

使用rewre with Jest监视在私有函数中使用的console.log

  •  1
  • Gary  · 技术社区  · 6 年前

    我在一个文件中有一个私有函数,它使用 console.log . 我想查一下 真的跑了,在我的 Jest rewire .

    我有以下文件:

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

    suggested here 替换 用一个滑稽的模拟函数 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]
    

    有没有办法监视 在私人场合使用时?

    1 回复  |  直到 6 年前
        1
  •  3
  •   Brian Adams    6 年前

    跟踪你的嘲笑 __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();
    });