首页 > 解决方案 > 模拟命名导出以使用 Jest 进行测试

问题描述

我有一个Helper.js文件,其中包含以下几个帮助函数,这些函数正在不同的组件中使用。

    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(){
           .....
      }

这是一个使用Helper.js文件中定义的函数的组件。我正在为组件编写测试,我想模拟这里调用的外部函数。

    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>
            );
         };
     }

我是 Jest/Enzyme 的新手,我无法弄清楚如何模拟外部函数 buildOptions。我无法弄清楚如何模拟外部 buildOptions 函数。有人可以帮我解决这个问题吗?这是我的测试代码:

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
}); 

标签: unit-testingmockingjestjs

解决方案


因为你想模拟一个命名的导出函数,所以有一个特殊的技巧,它涉及在你的测试之前使用一个导入所有命名的导出。*

// 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');
}); 

推荐阅读