How can i get window.location.pathname on my test file using Jest?

坚强是说给别人听的谎言 提交于 2019-12-01 20:31:52

Add testURL into your configuration file. For example( package.json ):

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

By default jest set window.location.href as "about:blank". After setting testURL, jest use it as test environment url and location.href receive that value.

You can read about it: https://facebook.github.io/jest/docs/en/configuration.html#testurl-string

I'm not sure that I get the logic of your component, but I suggested to use methods of react-router, instead of window.location. To push user to specific page use:

browserHistory.push('/login');

As a result the test can be written significantly easier, use spy() from Sinon.js or spy from Jest https://facebook.github.io/jest/docs/mock-functions.html

Example with spy:

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

So, the idea is test whether or not methods which has to change location is called with correct params.

Try use: expect(location.pathname).to.equal('/login').

In my tests the location is a global variable, you can get as if it was window.location, and if you need the fullpath, try: location.href.

Finally found the solution !

so you can set the base URL in your Jest config section in your package.json

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

And for the unit test you can change the window.location.pathname via:

window.history.pushState({}, 'Page Title', '/any/url/you/like?with=params&enjoy=true');
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!