[英]How do you test router match params with jest and enzyme?
假設我有以下組件,我從https://www.codeday.top/2017/11/08/56644.html 中獲取。 在這里,我使用 match.params 來訪問 id。 我將如何為此組件編寫單元測試以使用 Jest+Enzyme+Typescript+React 測試 h2 元素的存在。
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { Route, BrowserRouter as Router, Link, match } from 'react-router-dom';
// define React components for multiple pages
class Home extends React.Component<any, any> {
render() {
return (
<div>
<div>HOME</div>
<div><Link to='/details/id123'>Goto Details</Link></div>
</div>);
}
}
interface DetailParams {
id: string;
}
interface DetailsProps {
required: string;
match?: match<DetailParams>;
}
class Details extends React.Component<DetailsProps, any> {
render() {
const match = this.props.match;
if (match) {
return (
<div>
<h2>Details for {match.params.id}</h2>
<Link to='/'>Goto Home</Link>
</div>
);
} else {
return (
<div>
<div>Error Will Robinson</div>
<Link to='/'>Goto Home</Link>
</div>
)
}
}
}
ReactDOM.render(
<Router>
<div>
<Route exact path="/" component={Home} />
<Route exact path="/details/:id" component={(props) => <Details required="some string" {...props} />} />
</div>
</Router>
, document.getElementById('root')
);
const wrapper = shallow(
<Details
required={true}
match={{params: {id: 1}, isExact: true, path: "", url: ""}}
/>
);
expect(wrapper.containsMatchingElement(<h2>Details for 1</h2>)).toBeTruthy();
路由器存在於上下文中,因此您可以將測試包裝在上下文中並為其提供匹配參數以測試您的組件如何獲取它們。
import { BrowserRouter } from 'react-router-dom';
import { shape } from 'prop-types';
import { mount } from 'enzyme';
// Instantiate router context
const router = route => ({
history: new BrowserRouter().history,
route,
});
const createContext = route => ({
context: { ...router(route) },
childContextTypes: { router: shape({}) },
});
export function mountWrap(node, route) {
return mount(node, createContext(route));
}
示例描述:
import React from 'react';
import { TableC } from '../../src/tablec';
import { mountWrap, shallowWrap } from '../testhelp/contextWrap';
import { expectedProps } from './mockdata'
describe('Table', () => {
let props;
let component;
let route = {
location: {},
match: {[MATCH OBJ HERE]}
}
const wrappedMount = () => mountWrap(<TableC {...props} />, route);
beforeEach(() => {
props = {
query: {
data: tableData,
refetch: jest.fn(),
},
};
if (component) component.unmount();
});
test('should call a DeepTable with correct props', () => {
let route = {
location: {},
match: {[UPDATE MATCH OBJ HERE BEFORE TEST]}
}
const wrapper = wrappedMount();
expect(wrapper.find('DeepTable').props()).toEqual(expectedProps);
});
});
這也允許您有選擇地向上下文添加其他內容,並允許包裝器中的頂級對象成為您的組件(與使用 BrowserRouter 或 StaticRouter 包裝相反)
const wrapper = mount(
<MemoryRouter initialEntries={['/1234']}>
<Route exact path="/:id/" component={Details} />
</MemoryRouter>
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.