【问题标题】:How to mock Material-UI withWidth HOC如何使用Width HOC模拟Material-UI
【发布时间】:2019-03-27 12:53:36
【问题描述】:

假设我有一个包含在 Material-UI 的 withWidth HOC 中的组件。您如何使用 jest 模拟 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 模拟返回值。

【问题讨论】:

    标签: reactjs mocking material-ui jestjs


    【解决方案1】:

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

    您可以简单地在挂载中传递 width 属性,这基本上是在模拟。见demo.test.jshttps://codesandbox.io/s/m9o783rox

    【讨论】:

      猜你喜欢
      • 2018-11-20
      • 1970-01-01
      • 2019-02-02
      • 2020-02-02
      • 2023-03-07
      • 2021-10-06
      • 2020-02-04
      • 1970-01-01
      • 2019-10-04
      相关资源
      最近更新 更多