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

使用jest测试另一个函数内部的函数

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

    我如何使用jest测试下面的代码片段。我正在尝试测试Winston自定义格式 printf

    // sample.js
    
    import {aa:{b}} = require("thirparty-package")
    
    const a = () => {
       return b((log) => {
         return `log message will be ${log.message}`
       })
    }
    
    module.exports = {
      a
    }
    
    
    // sample.test.js
    const customFunctions = require('./sample')
    
    test('should check b function is called and returns a string', () => {
       expect(customFunctions.a).toHaveBeenCalled() // throwing error 
        //jest.fn() value must be a mock function or spy.
    })
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   Estus Flask    6 年前

    如果是 b 那需要测试,那应该是个间谍,而不是 a .

    应模拟第三方模块(a demo ):

    const bMock = jest.fn();
    jest.mock('thirparty-package', () => ({ aa: { b: bMock } }));
    const { a } = require('./sample');
    a();
    const callback = bMock.mock.calls[0][0]; 
    expect(callback).toEqual(expect.any(Function));
    expect(callback({ message: 'foo' })).toBe('log message will be foo');