Is there any way to mock private functions with Jest?

前端 未结 4 1764
遥遥无期
遥遥无期 2020-12-10 01:36

The ES6 module that I want to test looks as follows:

function privateFunction() {
   ...
}
export function publicFunction() {
   ... does something ...
   pr         


        
4条回答
  •  遥遥无期
    2020-12-10 01:42

    I found out a way to mock my private function by using the babel-plugin-rewire module.

    In package.json I have the following:

      "devDependencies": {
        ...
        "babel-plugin-rewire": "1.0.0-beta-5",
        "babel-jest": "18.0.0",
        ...
    

    In .babel.rc I have the following:

    {
      "presets": [
        "es2015",
        "stage-0",
        "react"
      ],
      "env": {
        "test": {
          "plugins": [
            "babel-plugin-rewire"
          ]
        }
      },
      ...
    

    At this point I was able to mock the private function:

    import * as moduleToTest from './moduleToTest.js'
    
    describe('#publicFunction', () => {
      it('mocks private function', () => {
        moduleToTest.__Rewire__('privateFunction', () => { console.log('I am the mocked private function') })
        ...
      })
    })
    

提交回复
热议问题