如何使用Width HOC模拟Material-UI

时间:2018-10-23 10:09:06

标签: reactjs mocking material-ui jestjs

假设我有一个包装在Material-UI的withWidth HOC中的组件。如何使用玩笑来模拟withWidth的isWidthUp函数以返回预定的布尔值?

SUT

import React, { Component } from 'react';
import withWidth, { isWidthUp } from '@material-ui/core/withWidth';

class ComponentWithWidth extends Component {

    render() {
        const { width } = this.props;

        return isWidthUp('md', width)
            ? <p>above md</p>
            : <p>below md</p>;
    }
}

export default withWidth()(ComponentWithWidth);

我尝试过的事情

尝试1

import React from 'react';
import { configure, mount } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import ComponentWithWidth from '../ComponentWithWidth';
import { isWidthUp } from '@material-ui/core/withWidth';

configure({ adapter: new Adapter() });

jest.mock('@material-ui/core/withWidth');

describe('ComponentWithWidth', () => {

    it('Should render', () => {

        isWidthUp = jest.fn().mockReturnValue(true);

        const el = mount(<ComponentWithWidth />);
    });
});

问题

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

尝试2

import React from 'react';
import { configure, mount } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import ComponentWithWidth from '../ComponentWithWidth';
import withWidth from '@material-ui/core/withWidth';

configure({ adapter: new Adapter() });

describe('ComponentWithWidth', () => {

    it('Should render', () => {

        withWidth.isWidthUp = jest.fn().mockReturnValue(false);

        const el = mount(<ComponentWithWidth />);
    });
});

问题

该组件无视widthWidth.isWidthUp模拟返回值。

1 个答案:

答案 0 :(得分:1)

我对esmodules模拟并不熟悉,但我确实认为您不应以这种方式进行测试(即测试实现细节)。

您可以简单地将width道具传递给坐骑,这基本上是在嘲笑。参见demo.test.jshttps://codesandbox.io/s/m9o783rox