2017-04-23 23 views
1

私は反応のアプリはテストのための農薬と酵素を使用して作成する - 反応 - アプリJestを使用してテストファイルにwindow.location.pathnameを取得するにはどうすればよいですか?

私はどのように私のテストファイル内にwindow.location.pathnameの値を得ることができますか?

これは私のスペック

import React from 'react'; 
import MovieDetailsBox from '../../src/components/movie_single/MovieDetailsBox'; 
import { expect } from 'chai'; 
import { shallow } from 'enzyme'; 
import { movie_details } from '../../src/data/movies_details' 
import { empty_user } from '../../src/helper/sessionHelper'; 

jest.mock('react-router'); 

describe('Test <MovieDetailsBox /> Component',() => { 

    let movie_details_props = { 
     movie: {...movie_details} 
    } 

    let user_props = { 

    } 

    const context = { router: { isActive: (a, b) => true } } 

    const wrapper = shallow(
     <MovieDetailsBox movie={movie_details_props} 
         user={user_props} 
         currentPath={'/movie/68'}/>, { context } 
    ) 

    const movie_data_check = movie_details_props.movie; 

    it('MovieDetailsBox call correct function on rating box',() => { 
     wrapper.find('.hidden-xs .rate-movie-action-box button').simulate('click') 

     if(!empty_user(user_props)){ 
      expect(window.location.pathname).to.equal('/login') 
     } else { 
      console.log('have user wow') 
     } 
    }) 
}) 

ですが、私はそれがwindow.location.pathname戻り、空白の代わりに、現在のURLパス名のように思える私のコンソール上にエラー

AssertionError: expected 'blank' to equal '/login' 

としてこれを得ました。

これを修正するにはどうすればよいですか、setupTests.jsファイル内に何か他のものをセットアップする必要がありますか?

ありがとうございます!

+0

あなたはMovieDetailsBoxのためのコードを共有することはできますか? –

+0

これは 'class MovieDetailsBox extends Component'からの通常の反応コンポーネントです –

答えて

0

あなたのコンポーネントのロジックがわからないのですが、私はwindow.locationではなくreact-routerのメソッドを使うことを提案しました。 は、特定のページに使用するユーザーをプッシュする:

browserHistory.push('/login'); 

テストを大幅に容易に書き込むことができ、その結果、https://facebook.github.io/jest/docs/mock-functions.html

例スパイと冗談からSinon.js又はスパイからスパイ()を使用:

it('should redirect user to pathname=/delegation if pathname=/play',() => { 
    const spyBrowserHistory = spy(); 
    mobileDelegationRewireAPI.__Rewire__('browserHistory', { 
     push: spyBrowserHistory 
    }); 
    const wrapper = shallow(<MobileDelegation {...location} />); 
    wrapper.instance().componentDidMount(); 
    expect(spyBrowserHistory.calledOnce).to.be.true; 
    expect(spyBrowserHistory.calledWith(`/delegation${location.search}`)).to.be.true; 
}); 

したがって、場所を変更する必要のあるメソッドが正しいパラメータで呼び出されているかどうかは、テストです。

0

試用:expect(location.pathname).to.equal('/login')

私のテストでは、locationはグローバル変数で、あたかもそれがwindow.locationだったかのようになります。フルパスが必要な場合は、location.hrefを試してみてください。

2

設定ファイルにtestURLを追加します。例えば (package.json):

"jest": { 
.... 
    "testURL": "http://test.com/login" 
.... 
} 

":空白約" としてwindow.location.href設定されたデフォルトの冗談ことでは。 testURLを設定したら、テスト環境urlとしてjestを使用し、その値をlocation.hrefに渡します。

あなたはそれについて読むことができます: https://facebook.github.io/jest/docs/en/configuration.html#testurl-string

+0

私はほとんどすべてのアプローチを試しましたが、私は考えることができました。それはとても簡単でした...私にとってはRTFMでしょう。 –

関連する問題