gpt4 book ai didi

reactjs - 使用 Material-UI 进行 enzyme 浅层测试

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

我在我的应用程序中使用 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 创建了一个实际的 DOM 来使用。那么,有没有更好的方法来处理这个问题呢?我在互联网上花了一天的时间,到目前为止,还没有找到更好的方法的好例子。

谢谢!

最佳答案

天哪......我也花了一段时间才使其工作,但我在存储库页面中找到了一个工作示例。 material-ui 在 enzyme 的 shallowmount 之上有一个包装器,允许您潜水您想要的组件想测试一下。

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

这是the config that I followed ,同样在我的例子中,我必须在其他中执行一些操作后调用 component.update(); 才能看到我的状态更新。

关于reactjs - 使用 Material-UI 进行 enzyme 浅层测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52173088/

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