Search code examples
unit-testingmockingjestjs

Mock named exports for testing using Jest


I have a Helper.js file with several helper functions as below that is being used in different components.

    export function buildOptions(elem) { 
        var oList=[];   
        for (var i=0; i < field.length; i++) {
            oList.push (
              <option value={options[i]["id"]}>
                  {options[i][elem]}
              </option>
            )
         }    
         return oList;
      }

      export function B(){
           .....
      }

Here is a component which makes use of the function defined in Helper.js file. I am writing tests for the component and I would like to mock the external function being called here.

    import React from 'react';
    import ReactDOM from 'react-dom';
    import { buildOptions, A} from './Helper.js';

    class DemoComponent extends React.Component {
        constructor(props) {
            super(props);
        }

        add(e, index) {
            ....
        }


        render() {
            var o_list=buildOptions("name");

            return (
               <div>
                  ...
                  <select required className={selectClass}  >
                      {o_list}
                  </select>  
                  ...           
                  <button type="button" onClick={(e) => this.add(e, this.props.index)}>
                        Add 
                  </button>
               </div>
            );
         };
     }

I am new to Jest/Enzyme and I am unable to figure out how to mock the external function buildOptions. I am unable to figure out how to mock the external buildOptions function.Could anyone please help me with this. Here is my test code:

import React from 'react';
import { mount, shallow } from 'enzyme';
import { buildOptions } from '../components/Helper.js';
import DemoComponent from '../components/DemoComponent';

describe('Democomponent', () => {

  it('should render required elements', () => {

    const wrapper = shallow(
       <DemoComponent 
        index={0}/> 
    );
    //
    tests
}); 

Solution

  • Since you want to mock a named exported function, there is a special trick for that which involves importing all named exports with an * before your tests.

    // your test file
    import * as Helper from './Helper.js';
    
    const originalBuildOptions = Helper.buildOptions;
    Helper.buildOptions = jest.fn();
    
    beforeEach(() => {
      jest.clearAllMocks();
      // Reset to original implementation before each test
      Helper.buildOptions.mockImplementation(originalBuildOptions);
    });
    
    test('my test', () => {
      // Mock for this test only (will be restored by next `beforeEach` call)
      Helper.buildOptions.mockImplementation(() => 'your mock');
    });