2017-04-23 117 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') 
     } 
    }) 
}) 

但我得到了這是一個錯誤我的控制檯

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

好像window.location.pathname回報的空白,而不是當前的URL路徑名上。

那麼我該如何解決這個問題,或者我需要在setupTests.js文件中設置其他任何東西?

謝謝!

+0

你能爲MovieDetailsBox共享代碼? –

+0

這只是一個正常的反應組件從類'MovieDetailsBox擴展組件' –

回答

0

我不確定是否獲得了組件的邏輯,但我建議使用react-router的方法,而不是window.location。 要推到用戶特定的網頁使用:

browserHistory.push('/login'); 

作爲結果,測試可以被寫入顯著容易,使用間諜()從Sinon.js或間諜從玩笑有觀測https://facebook.github.io/jest/docs/mock-functions.html

實施例:

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,如果你需要的FULLPATH,嘗試:location.href

2

將testURL添加到您的配置文件中。 例如(的package.json):

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

默認設置開玩笑window.location.href爲 「約:空白」。在設置testURL之後,使用它作爲測試環境url和location.href接收該值。

你可以閱讀一下: https://facebook.github.io/jest/docs/en/configuration.html#testurl-string

+0

我試過幾乎所有其他方法,我可以找到,我可以想到,它是如此簡單... RTFM對我來說,我猜。 –

相關問題