Var*_*kul 3 reactjs jestjs enzyme create-react-app
我有React应用是通过用玩笑和酶进行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')
}
})
})
Run Code Online (Sandbox Code Playgroud)
但是我在控制台上将其作为错误
AssertionError: expected 'blank' to equal '/login'
Run Code Online (Sandbox Code Playgroud)
似乎window.location.pathname
返回空白而不是当前的URL路径名称。
那么我该如何解决此问题,还是需要在setupTests.js文件中设置其他设置?
谢谢!
小智 8
所以你可以在你的 Jest 配置部分设置基本 URL package.json
"jest": {
....
"testURL": "http://test.com/login"
....
}
Run Code Online (Sandbox Code Playgroud)
对于单元测试,您可以通过以下方式更改 window.location.pathname:
window.history.pushState({}, 'Page Title', '/any/url/you/like?with=params&enjoy=true');
Run Code Online (Sandbox Code Playgroud)
小智 5
将testURL添加到您的配置文件中。例如(package.json):
"jest": {
....
"testURL": "http://test.com/login"
....
}
Run Code Online (Sandbox Code Playgroud)
默认情况下,开玩笑将window.location.href设置为“ about:blank”。设置了testURL之后,请开玩笑地将其用作测试环境的url和location.href接收该值。
您可以阅读以下内容:https : //facebook.github.io/jest/docs/en/configuration.html#testurl-string
我不确定我是否了解您组件的逻辑,但我建议使用react-router的方法,而不是window.location。要将用户推送到特定页面,请使用:
browserHistory.push('/login');
Run Code Online (Sandbox Code Playgroud)
因此,可以更轻松地编写测试,使用来自Sinon.js的spy()或来自Jest的spy https://facebook.github.io/jest/docs/mock-functions.html
间谍示例:
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;
});
Run Code Online (Sandbox Code Playgroud)
因此,我们的想法是测试是否使用正确的参数调用必须更改位置的方法。
归档时间: |
|
查看次数: |
11289 次 |
最近记录: |