我有一个 React 组件,我正在尝试使用 Enzyme/Jest 对其进行测试。我试图找出最合适的测试来确保组件已呈现。
我的组件有一个 prop shouldRender
,如果为 false,将导致组件无法呈现。我的组件如下所示:
import React from 'react';
const propTypes = {
shouldRender: React.PropTypes.bool,
};
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
foo: 'bar',
};
}
render() {
if (!this.props.shouldRender) {
return null;
}
return (
<div>
<span>My component</span>
</div>
);
}
}
MyComponent.propTypes = propTypes;
export default MyComponent;
我有一个看起来像这样的测试:
import React from 'react';
import { shallow } from 'enzyme';
import MyComponent from '../MyComponent';
describe('MyComponent', () => {
it('Should render if we want it to', () => {
const component = shallow(<MyComponent shouldRender />);
expect(component).toBeDefined(); // Passes
});
it('Should not render if we do not want it to', () => {
const component = shallow(<MyComponent />);
expect(component).not.toBeDefined(); // Does not pass, as component isn't undefined.
});
});
我希望第二个测试失败,因为组件没有渲染。有没有更好的方法来测试组件是否已呈现?
如果需要,很乐意提供更多信息。
谢谢!