【问题标题】:Enzyme shallow testing with Material-UI使用 Material-UI 进行酶浅测试
【发布时间】:2018-09-04 19:46:46
【问题描述】:

我在我的应用程序中使用 Material UI。我有以下组件,我想测试一个有效的免责声明文本(注意我在这里使用的是 withStyles HOC):

import React from 'react';
import { object } from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
import { Typography } from '@material-ui/core';

const headerBarHeight = 64;

const styles = () => ({
    disclaimer: {
        position: 'absolute',
        bottom: headerBarHeight,
        padding: '0 0 5px 10px'
    }
});

const Disclaimer = props => {
    const { classes } = props;

    return (
        <div className={classes.disclaimer}>
            <Typography gutterBottom noWrap>
                Copyright StaticSphere { new Date().getFullYear() }
            </Typography>
        </div>
    );
};

Disclaimer.propTypes = {
    classes: object.isRequired
};

export default withStyles(styles)(Disclaimer);

我要做的是编写一个测试来验证年份是否正确:

import React from 'react';
import { shallow } from 'enzyme';
import { Typography } from '@material-ui/core';

import Disclaimer from 'components/Shell/Disclaimer';

describe('Disclaimer', () => {
    it('displays the proper year', () => {
        var component = shallow(
            <Disclaimer />
        );

        var year = new Date().getFullYear();
        var text = component.find(Typography).text();

        expect(text).toBe(`Copyright StaticSphere ${year}`);
    });
});

这不起作用。测试抱怨它找不到 Typography 组件。查看文档,这是意料之中的,因为 Typography 不是根组件。当我将测试更改为使用 mount 时,一切正常。

也就是说,我已经读过我应该尽可能地尝试使用 shallow,因为 mount 创建了一个实际的 DOM 来使用。那么,有没有更好的方法来处理这个问题?我在互联网上花了一天的时间,到目前为止,还没有找到更好的方法。

谢谢!

【问题讨论】:

  • 你试过var text = component.dive().find(Typography).text(); 吗?
  • 我尝试了各种潜水组合,但无法完全按照我想要的方式工作。我尝试了各种版本的潜水(),并不能完全让它工作。 mount() 工作正常。
  • 这能回答你的问题吗? Ignore HOC when testing React Components

标签: reactjs enzyme


【解决方案1】:

OMG.... 我也花了一段时间才让它工作,但我在 repo 的页面中找到了一个工作示例。 material-ui 在酶的 shallowmount 之上有一个包装,允许您 dive 要测试的组件。

shallow = createShallow({ dive: true }); 让我开心。

这是the config that I followed,在我的情况下,我必须在其他地方进行一些操作后调用component.update();才能看到我的状态更新。

【讨论】:

    【解决方案2】:

    当您使用 HOC 时,我们需要使用 WrappedComponent 将 jsx 封装在其中。

     var component = shallow(
            <Disclaimer.WrappedComponent />
        ).dive(); 
    

    dive() will further shallow re-render Components like in our case it'sTypegraphy`.

    你可以不使用dive()试试这个

    除此之外,您还可以通过以下方式轻松访问 Typography:

    var text = component.find('withStyles(Typography)').text();
    

    希望对您有所帮助,如果问题仍然存在,请告诉我

    【讨论】:

    • 我尝试了各种版本的潜水,但无法完全发挥作用,但还是要感谢它。
    • 仅使用 WrappedComponent
    • 通过 github 分享。更容易调试问题
    猜你喜欢
    • 2021-06-04
    • 2019-12-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-09
    • 2019-09-25
    • 2020-08-26
    • 1970-01-01
    • 2018-04-05
    相关资源
    最近更新 更多