如何使用 Jest 获取测试文件上的 window.location.pathname?

2023-11-23

我有反应应用程序是由 create-react-app 使用笑话和酶进行测试制作的

那么我怎样才能得到的值window.location.pathname在我的测试文件中?

这是我的规格

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

但我在控制台上收到此错误

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

这好像是window.location.pathname返回空白而不是当前 url 路径名。

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

Thanks!


终于找到解决办法了!

所以你可以在你的 Jest 配置部分设置基本 URLpackage.json

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

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

window.history.pushState({}, 'Page Title', '/any/url/you/like?with=params&enjoy=true');
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 Jest 获取测试文件上的 window.location.pathname? 的相关文章

随机推荐