Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

112
Views
Cómo probar el enrutador de reacción con enzima

Estoy usando enzima+mocha+chai para probar mi proyecto react-redux. La enzima proporciona poca profundidad para probar el comportamiento del componente. Pero no encontré una manera de probar el enrutador. Estoy usando react-router como se muestra a continuación:

 <Router history={browserHistory}> ... <Route path="nurse/authorization" component{NurseAuthorization}/> ... </Route>

Quiero probar esta ruta nurse/authorization . Consulte el componente NurseAuthorization . ¿Cómo probarlo en el proyecto reactjs?

EDITAR1

Estoy usando react-router como el marco del enrutador.

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Puede envolver su enrutador dentro de un componente para probarlo.

Rutas.jsx

 export default props => ( <Router history={browserHistory}> ... <Route path="nurse/authorization" component{NurseAuthorization}/> ... </Route> )

índice.js

 import Routes from './Routes.jsx'; ... ReactDOM.render(<Routes />, document.getElementById('root'));

Luego, debe renderizar superficialmente su componente Routes y podrá crear un mapa de objetos para verificar la correspondencia entre la ruta y el componente relacionado.

Rutas.test.js

 import { shallow } from 'enzyme'; import { Route } from 'react-router'; import Routes from './Routes.jsx'; import NurseAuthorization from './NurseAuthorization.jsx'; it('renders correct routes', () => { const wrapper = shallow(<Routes />); const pathMap = wrapper.find(Route).reduce((pathMap, route) => { const routeProps = route.props(); pathMap[routeProps.path] = routeProps.component; return pathMap; }, {}); // { 'nurse/authorization' : NurseAuthorization, ... } expect(pathMap['nurse/authorization']).toBe(NurseAuthorization); });

EDITAR

En caso de que desee manejar adicionalmente el caso de los accesorios de renderizado:

 const pathMap = wrapper.find(Route).reduce((pathMap, route) => { const routeProps = route.props(); if (routeProps.component) { pathMap[routeProps.path] = routeProps.component; } else if (routeProps.render) { pathMap[routeProps.path] = routeProps.render({}).type; } return pathMap; }, {});

Funcionará solo en caso de que renderice directamente el componente que desea probar (sin envoltorio adicional).

 <Route path="nurse/authorization" render{() => <NurseAuthorization />}/>
over 4 years ago · Santiago Trujillo Report

0

Tenía mis rutas definidas en otro archivo para el enrutador dinámico, por lo que también estoy probando que todas las rutas que represento como Rutas estén definidas en mis constantes paths.js:

 it('Routes should only have paths declared in src/routing/paths.js', () => { const isDeclaredInPaths = (element, index, array) => { return pathsDefined.indexOf(array[index]) >= 0; } expect(routesDefined.every(isDeclaredInPaths)).to.be.true; });
over 4 years ago · Santiago Trujillo Report

0

Esto solo pasará si el componente se procesa correctamente: funciona con Redux y react-router, incluidos los ganchos.

 import React from "react"; import { expect } from "chai"; import { mount } from "enzyme"; import { MemoryRouter, Route } from "react-router-dom"; import { createMockStore } from "redux-test-utils"; import { Provider } from "react-redux"; ... describe("<MyComponent />", () => { it("renders the component", () => { let props = { index: 1, value: 1 }; let state = {}; const wrapper = mount( <Provider store={createMockStore(state)}> <MemoryRouter initialEntries={["/s/parameter1"]}> <Route path="/s/:camera"> <MyComponent {...props} /> </Route> </MemoryRouter> </Provider> ); expect(wrapper.find(ProcessedFrames.WrappedComponent)).to.have.lengthOf(1); }); });
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!