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

时间:2017-04-23 07:35:18

标签: reactjs jestjs enzyme create-react-app

我有反应应用程序是由create-react-app使用jest和酶进行测试

那么如何才能在我的测试文件中获得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返回空白而不是当前网址路径名称。

那我怎么能解决这个问题呢?我还需要在setupTests.js文件中设置其他内容吗?

谢谢!

4 个答案:

答案 0 :(得分:4)

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

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

默认情况下,jest将window.location.href设置为“about:blank”。设置testURL后,jest使用它作为测试环境url,location.href接收该值。

你可以读到它: https://facebook.github.io/jest/docs/en/configuration.html#testurl-string

答案 1 :(得分:0)

我不确定我是否获得了组件的逻辑,但我建议使用react-router的方法,而不是window.location。 要将用户推送到特定页面使用:

browserHistory.push('/login');

因此,可以更轻松地编写测试,使用Sinon.js中的spy()或来自Jest的间谍https://facebook.github.io/jest/docs/mock-functions.html

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

因此,我们的想法是测试是否使用正确的参数来调用必须改变位置的方法。

答案 2 :(得分:0)

尝试使用:expect(location.pathname).to.equal('/login')

在我的测试中,location是一个全局变量,您可以像window.location一样获得,如果需要完整路径,请尝试:location.href

答案 3 :(得分:0)

最终找到了解决方案!

因此您可以在package.json

的Jest配置部分中设置基本URL。
"jest": {
 ....
    "testURL": "http://test.com/login"
 ....
 }

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

window.history.pushState({}, 'Page Title', '/any/url/you/like?with=params&enjoy=true');