gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 14:18:19 24 4
gpt4 key购买 nike

假设我有一个组件,它包装在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com