我有一个名为prop的组件Typography
,该组件需要一个variant
prop并相应地渲染一个元素。
Typography.js
为了简洁起见,省略了很多
import { StyledH1, ... } from './Typography.styles';
const variantMapping = {h1: StyledH1, ...};
const Typography = ({ children, ...props }) => {
const Component = variantMapping[props.variant] ? variantMapping[props.variant] : 'span';
return <Component {...props}>{children}</Component>;
};
因此,我尝试了许多方法来进行工作测试。现在,我正在尝试通过variant="h1"
,获取以下标记<h1 class="..styled component what nots...">...</h1>
并验证<h1>
渲染
Typography.spec.js
import { mount } from 'enzyme';
import Typography from '.';
describe('<Typography />', () => {
it('renders H1', () => {
const wrapper = mount(<Typography variant="h1" />);
const elem = wrapper;
console.log(elem.debug());
expect(wrapper.find('h1')).toEqual(true);
});
});
所以运行调试器我回来了
console.log components/Typography/Typography.spec.js:9
<Typography variant="h1" bold={false} transform={{...}} small={false}>
<Typographystyles__StyledH1 variant="h1" bold={false} transform={{...}} small={false}>
<StyledComponent variant="h1" bold={false} transform={{...}} small={false} forwardedComponent={{...}} forwardedRef={{...}}>
<h1 transform={{...}} className="Typographystyles__StyledH1-sc-1n6ui1k-0 bvGdAG" />
</StyledComponent>
</Typographystyles__StyledH1>
</Typography>
所以我更改了element变量以查找h1元素 const elem = wrapper.find('h1');
调试器返回
console.log components/Typography/Typography.spec.js:9
<h1 transform={{...}} className="Typographystyles__StyledH1-sc-1n6ui1k-0 bvGdAG" />
我不确定这是否是正确的方法,只是想尝试至少通过一项合理的测试即可。
此时,expect
我写的每条语句都会返回错误或失败
expect(elem).to.have.lengthOf(1);
TypeError:无法读取未定义的属性“具有”expect(elem.contains('h1')).to.equal(true);
TypeError:无法读取未定义的属性“等于”expect(elem.contains('h1')).toEqual(true);
Expect(received).toEqual(expected)//深度相等尝试了更多的选择,但没有任何结果。任何帮助将不胜感激。
因此,似乎expect
没有设置我使用酶的断言。在进一步阅读Enzyme文档后,我的设置仅使用适配器,以简化组件的渲染/安装。我没有使用文档中的酶断言的能力,因为未安装它们。为了回答这个特定的问题,我必须使用Jest断言。
describe('<Typography />', () => {
it('renders h1', () => {
const wrapper = mount(<Typography variant="h1" />);
const elem = wrapper.find('h1');
expect(elem.length).toBe(1);
});
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句