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

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

问题描述

我有反应的应用程序是通过用玩笑和酶进行测试的create-react-app制作的

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?

谢谢!

推荐答案

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

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

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

默认情况下,玩笑将window.location.href设置为"about:blank".设置了testURL之后,最好将它用作测试环境的url和location.href会收到该值.

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.

您可以阅读以下内容: https://facebook.github.io/jest/docs/en /configuration.html#testurl-string

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

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

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