Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 516
Varis Darasirikul Avatar asked Apr 23 '17 07:04

Varis Darasirikul


1 Answers

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');
like image 87
Mustafa J Avatar answered Sep 24 '22 16:09

Mustafa J