我正在尝试测试一个组件的一部分,如果浏览器没有Flash插件,该组件将不会显示。该组件在swfObject和下面提到的逻辑的帮助下检测flash插件。
MyComponent.js
export default class MyComponent extends Component {
static propTypes = {
// props...
};
static contextTypes = {
router: PropTypes.object.isRequired,
};
constructor() {
super();
this.state = {
isMobile: true
};
}
componentDidMount() {
const flashVersion = require('../../../client/utils/detectFlash')();
if ((flashVersion && flashVersion.major !== 0)) {
/* eslint-disable */
this.setState({isMobile: false});
/* eslint-enable */
}
}
//...
render() {
//...
return (
//...
{ !this.state.isMobile && (
<div className="xyz">
<p>XYZ: this content only shows up when flash has been detected</p>
</div>)
}
);
}
}
MyComponent-test.js
import React from 'react';
import {mount} from 'enzyme';
import chai, {expect} from 'chai';
import chaiEnzyme from 'chai-enzyme';
import configureStore from 'redux-mock-store';
import { Provider } from 'react-redux';
import {MyComponent} from '../../common/components';
chai.use(chaiEnzyme());
describe('<MyComponent />', () => {
describe('mobile/flash disabled', () => {
const mockStore = configureStore({});
const store = mockStore({});
it('Does not render xyz', () => {
const wrapper = mount(
<Provider store={store} key="provider">
<MyComponent {...params}/>
</Provider>
);
expect(wrapper.find('.xyz').to.have.length(0));
});
});
});
问题是这个.state.isMobile被设置为false,因为karma启动chrome并检测到flash插件。你可以想象,如果需要手动禁用Chrome的flash插件,测试也无法工作。
测试swfObject是否正常工作并不是测试的目的。
最好的方法是颠倒依赖关系,每当客户端在MyComponent
之外移动时,将责任转移到检查中,并将其作为道具传入。这被称为依赖反转原理。
对于测试,您可以运行一个prop设置为true的测试,另一个设置为false的测试。
因此,您将拥有<MyComponent isMobile={true} />
,并在调用代码中调用swfObject。