从默认导入开玩笑的模拟异步功能

时间:2018-09-21 10:45:36

标签: javascript reactjs unit-testing react-native jestjs

我正在尝试模拟作为默认导出导出的异步函数,但我得到的只是 TypeError:无法读取未定义的属性'then'

我要模拟的是 config.js

const configureEnvironment = async (nativeConfig) => {
    return { await whatever() }
}

我正在测试的文件是 Scene.js

import configureEnvironment from './config';

class Scene extends React.Component {
    constructor(props) {
        nativeConfig = {};
        configureEnfironment(nativeConfig).then((config) => {
            // Do stuff
        }
    }
}

我的测试文件是 Scene.test.js

let getScene = null;
const configureEnvironmentMock = jest.fn();

describe('Scene', () => {
    jest.mock('./config', () => configureEnvironmentMock);

    const Scene = require('./Scene').default;

    getScene = (previousState) => {
        return shallow(
            <Scene prevState={previousState}>
                <Fragment />
            </Scene>,
        );
    };

    it('calls configureEnvironment with the nativeConfig', async () => {
        expect.assertions(1);
        const nativeConfig = {};

        getScene(nativeConfig);

        expect(configureEnvironmentMock).toHaveBeenCalledWith(nativeConfig);
    });
});

但是,运行测试的结果是:

TypeError: Cannot read property 'then' of undefined

我了解问题出在我模拟configureEnvironment的方式上,但是我无法使其正常工作。

我还尝试过模拟以下功能:

jest.mock('./config', () => {
    return {
        default: configureEnvironmentMock,
    };
});

但结果是:

TypeError: (0 , _config2.default) is not a function

2 个答案:

答案 0 :(得分:1)

模拟模块默认导出的一种干净简单的方法是结合使用jest.spyOnmockImplementation之类的功能。


这是一个基于上面的代码片段的工作示例:

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

答案 1 :(得分:0)

您可以开玩笑地嘲笑任何东西,像这样 jest.mock('@material-ui/core/withWidth', () => ({ __esModule: true, isWidthUp: jest.fn((a, b) => true), default: jest.fn(fn => fn => fn) }))