【发布时间】: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