Jest mock async function from default import

后端 未结 2 2018
-上瘾入骨i
-上瘾入骨i 2021-01-19 08:03

I\'m trying to mock an async function that is exported as a default export but all I get is TypeError: Cannot read property \'then\' of undefined

Wh

相关标签:
2条回答
  • 2021-01-19 08:09

    You can mock anything with jest, like this jest.mock('@material-ui/core/withWidth', () => ({ __esModule: true, isWidthUp: jest.fn((a, b) => true), default: jest.fn(fn => fn => fn) }))

    0 讨论(0)
  • 2021-01-19 08:23

    A clean and simple way to mock the default export of a module is to use jest.spyOn in combination with functions like mockImplementation.


    Here is a working example based on the code snippets above:

    config.js

    const whatever = async () => 'result';
    
    const configureEnvironment = async (nativeConfig) => await whatever();
    
    export default configureEnvironment;
    

    Scene.js

    import * as React from 'react';
    import configureEnvironment from './config';
    
    export class Scene extends React.Component {
      constructor(props) {
        super(props);
        configureEnvironment(props.prevState).then((config) => {
          // Do stuff
        });
      }
      render() {
        return null;
      }
    }
    

    Scene.test.js

    import React, { Fragment } from 'react';
    import { shallow } from 'enzyme';
    
    import { Scene } from './Scene';
    import * as config from './config';
    
    describe('Scene', () => {
    
      const mock = jest.spyOn(config, 'default'); // spy on the default export of config
      mock.mockImplementation(() => Promise.resolve('config')); // replace the implementation
    
      const getScene = (previousState) => {
        return shallow(
          <Scene prevState={previousState}>
            <Fragment />
          </Scene>,
        );
      };
    
      it('calls configureEnvironment with the nativeConfig', async () => {
        expect.assertions(1);
        const nativeConfig = {};
    
        getScene(nativeConfig);
    
        expect(mock).lastCalledWith(nativeConfig);  // SUCCESS
      });
    });
    
    0 讨论(0)
提交回复
热议问题