Javascript 在禁用浏览器闪存插件的情况下运行Karma测试
我正在尝试测试一个组件的一部分,如果浏览器没有Flash插件,它将不会显示。该组件通过和下面提到的逻辑检测flash插件Javascript 在禁用浏览器闪存插件的情况下运行Karma测试,javascript,reactjs,karma-runner,chai,enzyme,Javascript,Reactjs,Karma Runner,Chai,Enzyme,我正在尝试测试一个组件的一部分,如果浏览器没有Flash插件,它将不会显示。该组件通过和下面提到的逻辑检测flash插件 MyComponent.js export default class MyComponent extends Component { static propTypes = { // props... }; static contextTypes = { router: PropTypes.object.isRequired, };
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>)
}
);
}
}
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));
});
});
});
问题是,当karma启动chrome并检测到flash插件时,this.state.isMobile被设置为false。您可以想象,如果需要手动禁用Chrome的flash插件,测试也无法工作。测试swfObject是否正常工作并不是测试的目的 最好的方法是颠倒依赖关系,将检查责任转移到客户机在
MyComponent
之外移动时,并将其作为道具传入。这就是所谓的
对于该测试,您可以在prop设置为true的情况下运行一个测试,在prop设置为false的情况下运行另一个测试
因此,您需要
并在调用代码中调用swfObject。我同意,而且我实际上会说检查应该发生在根组件上,并反映状态。然而,为了这次测试的目的,我希望避免这样的改变。你可以两者都做。当给定isMobile属性时,请使用它,否则请使用swfObject。那么变化就没有那么大了。