我有一個React組件,我正在試圖使用Enzyme/Jest進行測試。我想弄清楚什麼是最合適的測試,以確保組件已經呈現。測試React組件是否已呈現
我的組件有一個道具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.
});
});
我想第二次測試失敗,因爲該組件沒有渲染。有沒有更好的方法來測試組件是否已經呈現?
如果需要,歡迎提供更多信息。
謝謝!
只是一個通知。根據docs返回未定義'render'不是一個有效的選項。 「你也可以返回'null'或'false'來表示你不想渲染任何東西。」 –
Woops - 我只是在現場爲手冊寫了一個更簡化的版本 - 我將修復代碼現在。謝謝! –
順便說一下'isEmpty'方法。 https://github.com/airbnb/enzyme/blob/master/docs/api/ShallowWrapper/isEmpty.md –