简体   繁体   English

开玩笑地使用 spyOn 模拟嵌套的 function,但仍然调用实际的 function

[英]Jest mock nested function by using spyOn, but still call the actual function

getInfo calls getColor in the same file. getInfo在同一个文件中调用getColor My intention is to mock getColor function, I import the func.js as a module and spyOn getColor .我的意图是模拟getColor function,我将 func.js 作为模块导入并 spyOn getColor The mocked getColor is supposed to return "Red", but it still calls the actual function and returns "Black".模拟的getColor应该返回“Red”,但它仍然调用实际的 function 并返回“Black”。

Function File Function 文件

// func.js
function getColor() {
    return "black"
}

function getInfo(){
    const color = getColor()
    const size = "L"
    return `${color}-${size}`
}

module.exports = { getColor, getInfo }

Test File测试文件

// func.test.js
const func = require("./func")

describe("Coverage Change Test", () => {
  beforeAll(() => {
    const colorMock = jest.spyOn(func, "getColor"); // spy on otherFn
    colorMock.mockImplementation(() => "Red");
  });

  afterAll(() => {
    colorMock.resetAllMocks();
  })

  test("return Large Red", async () => {
    const res = func.getInfo();
    expect(res).toEqual("Red-L");
  });
});

I also tried requireActual , but it also calls the actual one.我也尝试过requireActual ,但它也调用了实际的。

const { getInfo, getColor } = require('./func');

jest.mock('./func', () => ({
  ...jest.requireActual('./func.'),
  getColor: jest.fn().mockImplementation(() => 'Red'),
}))

describe('test', () => {
  test('returns red', () => {
    const res = getInfo()
    expect(res).toEqual("Red-L")
  })
})

How can I properly mock up a nested function in Jest?如何在 Jest 中正确模拟嵌套的 function? Thanks in advance.提前致谢。

You're spying on func.getColor and mocking its implementation but getInfo is calling the locally scoped getColor function.您正在监视func.getColor和 mocking 的实现,但getInfo正在调用本地范围的getColor function。 You have to change the way getColor is being called to be able to mock it.您必须更改调用getColor的方式才能模拟它。

exports.getColor = function() {
  return 'black'
}

exports.getInfo = function() {
  const color = exports.getColor()
  const size = 'L'
  return `${color}-${size}`
}

Use rewire module to rewrite your exported properties.使用rewire模块重写导出的属性。

Your test file will look like this:您的测试文件将如下所示:

const rewire = require('rewire')

describe('test', () => {
  let func;
  let getColorSpy;
  beforeEach(() => {
    getColorSpy = jest.fn()
    func = rewire(__dirname + '/func.js') // import
    func.__set__('getColor', getColorSpy) // rewrite content of getColor
  })
  test('should return Red-L when getColor returns Red', () => {
    getColorSpy.mockReturnValue('Red')

    const res = func.getInfo()

    expect(res).toEqual("Red-L")
  })
})

Try to avoid write code like your module.尽量避免编写像你的模块这样的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM