如何使用 Jest 在我的测试文件中获取 window.location.pathname? [英] How can i get window.location.pathname on my test file using Jest?

查看:25
本文介绍了如何使用 Jest 在我的测试文件中获取 window.location.pathname?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 react 应用程序是通过 create-react-app 使用 jest 和酶进行测试的

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

那么如何在我的测试文件中获取 window.location.pathname 的值?

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

这是我的规格

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'

似乎 window.location.pathname 返回空白而不是当前的 url 路径名.

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

那么我该如何解决这个问题,或者我需要在 setupTests.js 文件中设置任何其他内容?

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

谢谢!

推荐答案

终于找到解决方案了!

因此您可以在 package.json

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

对于单元测试,您可以通过以下方式更改 window.location.pathname:

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

这篇关于如何使用 Jest 在我的测试文件中获取 window.location.pathname?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆