reactjs - 如何使用Width HOC模拟Material-UI

标签 reactjs mocking material-ui jestjs

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

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 模拟返回值。

最佳答案

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

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

关于reactjs - 如何使用Width HOC模拟Material-UI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52946433/

相关文章:

reactjs - 覆盖 Material UI 扩展面板摘要

javascript - React Native 从外部源加载 JSX 并在运行时对其进行转换

reactjs - 如何使用高阶组件访问状态

javascript - 你如何创建一个功能组件来更新 Redux store 的变化?

java - 如何使用PowerMock测试方法Jsoup.connect(静态)?

reactjs - React DnD 拖动时显示整个列表

javascript - 我们必须为哪些地方和哪些元素提供唯一 key ?

ruby - RSpec 模拟 :each block

grails - Grails 2.0 错误中的模拟测试

reactjs - 如何更改 MuiInputBase-root 的宽度?