我需要测试样式组件的状态或CSS属性。这是我的组件:
import React, { useState, useRef } from 'react';
import styled from 'styled-components';
import ArrowTemplate from './ArrowTemplate';
const Accordion = props => {
const content = useRef(null);
const [isAccordionExpanded, setIsAccordionExpanded] = useState(false);
const toggleAccordion = () => {
setIsAccordionExpanded(!isAccordionExpanded);
};
return (
<AccordionSection>
<AccordionBtn onClick={toggleAccordion}>
<AccordionTitle>
{props.title}
</AccordionTitle>
<ArrowTemplate
direction={isAccordionExpanded === false ? 'up' : 'down'}
onClick={toggleAccordion}
/>
</AccordionBtn>
<AccordionContent
ref={content}
isAccordionExpanded={isAccordionExpanded}
height={content.current === null ? '0' : content.current.scrollHeight}
>
<AccordionText>
{props.content}
</AccordionText>
</AccordionContent>
</AccordionSection>
);
};
export const AccordionBtn = styled.button`
background-color: #eee;
color: #444;
cursor: pointer;
padding: 18px;
display: flex;
align-items: center;
border: none;
outline: none;
:hover,
:focus,
:active {
background-color: #ccc;
}
`;
export const AccordionTitle = styled.p`
font-family: "Open Sans", sans-serif;
font-weight: 600;
font-size: 14px;
`;
export const AccordionContent = styled.div`
max-height: ${({ isAccordionExpanded, height }) => (isAccordionExpanded ? height : '0')}px;
background-color: red;
overflow: hidden;
transition: max-height 0.7s;
`;
export const AccordionText = styled.div`
font-family: "Open Sans", sans-serif;
font-weight: 400;
font-size: 14px;
padding: 18px;
`;
export const AccordionSection = styled.div`
display: flex;
flex-direction: column;
`;
export default Accordion;
这是我的测试:
import React from 'react';
import { mount, configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import Accordion, { AccordionBtn, AccordionContent } from '../Accordion';
configure({ adapter: new Adapter() });
describe('<Accordion/>',
() => {
let wrapper;
beforeEach(() => {
wrapper = mount(<Accordion/>);
});
it('should change state onClick', () => {
wrapper.find(AccordionBtn).simulate('click');
console.log(wrapper.find(AccordionContent).props());
expect(wrapper.find(AccordionContent)).toHaveProperty('max-height', '1px'); // This returns [] for max-height and {} for 1px
});
});
如何检查以下其中一项:
a)如果调用了setIsAccordionExpanded或toggleAccordion。
b)如果AccordionContent中的最大高度大于0px?