我有react应用程序是由create-react-app使用jest和 enzyme 进行测试制作的
那么我如何获取测试文件中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 文件中设置其他内容吗?
谢谢!
最佳答案
终于找到解决方案了!
这样您就可以在 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');
关于reactjs - 如何使用 Jest 获取测试文件上的 window.location.pathname?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43568570/