2016-05-06 4 views
1

ブラウザーにFlashプラグインがない場合、表示されないコンポーネントの一部をテストしようとしています。コンポーネントは、swfObjectと下記のロジックの助けを借りてフラッシュプラグインを検出します。ブラウザーフラッシュプラグインによるKarmaテストの実行を無効にする

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)); 
    }); 
    }); 
}); 

問題は、カルマは、クロムやフラッシュプラグインが検出された起動としてthis.state.isMobileがfalseに設定されています。あなたが手動でChromeのフラッシュプラグインを無効にする必要がある場合は、テストがうまくいかないことも想像できるでしょう。

答えて

1

swfObjectが正しく動作するかどうかのテストは、テストに関するものではありません。

ベストプラクティスは、クライアントがMyComponent以外のモバイルになっているかどうかをチェックし、それを小道具として渡すだけで、依存関係を逆転させてチェックすることです。これはDependency inversion principleと呼ばれます。

テストでは、propをtrueに設定し、もう一方をfalseに設定してテストを実行できます。

<MyComponent isMobile={true} />があり、呼び出しコードでswfObjectを呼び出します。

+0

私は同意し、実際には、ルートコンポーネントでチェックが行われ、状態が反映されると言います。しかし、このテストの目的のために、私はそのような変化を避けることを望んでいました。 –

+0

あなたは両方を行うことができます。 isMobile propを指定するとswfObjectが使用されます。そして、その変化はそれほど大きくはありません。 – Christiaan

関連する問題