我想测试当status属性设置为FETCHING时我的LoadingIndicator组件是否加载到DOM中,并且当它是READY时不加载。现在我有这个:
Request.Unvalidated.Form[k]
组件本身如下所示:
import React from 'react';
import { assert } from 'chai';
import { shallow, mount } from 'enzyme';
import LoadingIndicator from '../../src/components/LoadingIndicator';
import { STATUSES } from '../../src/reducers/status';
describe('LoadingIndicator', () => {
it('should render when the status is FETCHING', () => {
const wrapper = shallow(<LoadingIndicator status={STATUSES.FETCHING} />);
assert.ok(wrapper);
});
it('should not render when the status is READY', () => {
const wrapper = mount(<LoadingIndicator status={STATUSES.READY} />);
assert.isNotOkay(wrapper);
});
});
这似乎不是检查它是否呈现的正确方法,但我得到了
import React, { PropTypes } from 'react';
import CircularProgress from 'material-ui/CircularProgress';
import { STATUSES } from '../reducers/status';
import '../styles/LoadingIndicator.scss';
export default class LoadingIndicator extends React.Component {
render() {
return (
this.props.status === STATUSES.READY ? null :
<div className="loader-div">
<CircularProgress className="loader" />
</div>
);
}
}
LoadingIndicator.propTypes = {
status: PropTypes.string.isRequired,
};
我知道如何根据给出的属性来正确测试此组件的加载情况吗?
感谢。
答案 0 :(得分:2)
嗨,所以我最终自己搞清楚了。我应该想到这样一个事实:由于我正在做一个浅渲染,我能够看看是否渲染div,所以我最终得到:
import React from 'react';
import { expect } from 'chai';
import { shallow } from 'enzyme';
import LoadingIndicator from '../../src/components/LoadingIndicator';
import { STATUSES } from '../../src/reducers/status';
describe('LoadingIndicator', () => {
it('should render when the status is FETCHING', () => {
const wrapper = shallow(<LoadingIndicator status={STATUSES.FETCHING} />);
expect(wrapper.find('div')).to.have.length(1);
});
it('should not render when the status is READY', () => {
const wrapper = shallow(<LoadingIndicator status={STATUSES.READY} />);
expect(wrapper.find('div')).to.have.length(0);
});
});
这是有效的(两者均为正/负测试)。
答案 1 :(得分:-2)
您可以查看The Component Lifecycle。
特别是shouldComponentUpdate()
。
从那以后,您可以简单地添加
shouldComponentUpdate(nextProps, nextState) {
if (...) {
return true;
}
else {
return false;
}
}
决定是否渲染此组件。