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

谁说胖子不能爱 提交于 2019-12-20 02:14:31

问题


I have react app was made by create-react-app using jest and enzyme for testing

So how can i get the value of window.location.pathname inside my test file?

This is my spec

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

But i got this as an error on my console

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

It seems like window.location.pathname return blank instead of current url path name.

So how can i fix this or am i need to setup anything else inside setupTests.js file?

Thanks!


回答1:


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




回答2:


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.




回答3:


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.




回答4:


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


来源:https://stackoverflow.com/questions/43568570/how-can-i-get-window-location-pathname-on-my-test-file-using-jest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!