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

268
Views
Enzima probando un componente de orden superior (HOC) de autenticación

Creé un componente de orden superior/componente compuesto para garantizar que un usuario esté autenticado antes de cargar el componente. Es muy básico, pero tengo algunos problemas para probarlo. Quiero probar los puntos a continuación, que son similares a las pruebas que ya tengo en otros lugares:

  • Representa el Componente (normalmente verifico buscando un nombre de clase específico del className )
  • Tiene props correctos (en mi caso authenticated )
  • Muestra el componente envuelto si está authenticated y se vuelve null si no

El HOC:

 import React from 'react'; import { connect } from 'react-redux'; import { createStructuredSelector } from 'reselect'; import { makeSelectAuthenticated } from 'containers/App/selectors'; export default function RequireAuth(ComposedComponent) { class AuthenticatedComponent extends React.Component { static contextTypes = { router: React.PropTypes.object, } static propTypes = { authenticated: React.PropTypes.bool, } componentWillMount() { if (!this.props.authenticated) this.context.router.push('/'); } componentWillUpdate(nextProps) { if (!nextProps.authenticated) this.context.router.push('/'); } render() { return ( <div className="authenticated"> { this.props.authenticated ? <ComposedComponent {...this.props} /> : null } </div> ); } } const mapStateToProps = createStructuredSelector({ authenticated: makeSelectAuthenticated(), }); return connect(mapStateToProps)(AuthenticatedComponent); }

Estoy usando enzyme y jest para mis pruebas, pero no he encontrado una manera de representar el HOC con éxito durante mis pruebas.

¿Algunas ideas?

Solución gracias a la respuesta a continuación:

 import React from 'react'; import { shallow, mount } from 'enzyme'; import { Provider } from 'react-redux'; import { AuthenticatedComponent } from '../index'; describe('AuthenticatedComponent', () => { let MockComponent; beforeEach(() => { MockComponent = () => <div />; MockComponent.displayName = 'MockComponent'; }); it('renders its children when authenticated', () => { const wrapper = shallow( <AuthenticatedComponent composedComponent={MockComponent} authenticated={true} />, { context: { router: { push: jest.fn() } } } ); expect(wrapper.find('MockComponent').length).toEqual(1); }); it('renders null when not authenticated', () => { const wrapper = shallow( <AuthenticatedComponent composedComponent={MockComponent} authenticated={false} />, { context: { router: { push: jest.fn() } } } ); expect(wrapper.find('MockComponent').length).toEqual(0); }); });
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

La parte "complicada" aquí es que su HOC devuelve un componente conectado, lo que hace que las pruebas sean más difíciles porque tiene dos capas de procesamiento superficial (el componente conectado y el componente real) y tiene que burlarse de la tienda redux.

En su lugar, podría definir el componente AuthenticatedComponent por adelantado y exportarlo como una exportación con nombre. De lo que puede probarlo independientemente de la connect como prueba cualquier otro componente:

 export class AuthenticatedComponent extends React.Component { static contextTypes = { router: React.PropTypes.object, } static propTypes = { authenticated: React.PropTypes.bool, composedComponent: React.PropTypes.any.isRequired, } componentWillMount() { if (!this.props.authenticated) this.context.router.push('/'); } componentWillUpdate(nextProps) { if (!nextProps.authenticated) this.context.router.push('/'); } render() { const ComposedComponent = this.props.composedComponent; return ( <div className="authenticated"> { this.props.authenticated ? <ComposedComponent {...this.props} /> : null } </div> ); } } export default function RequireAuth(ComposedComponent) { const mapStateToProps = () => { const selectIsAuthenticated = makeSelectAuthenticated(); return (state) => ({ authenticated: selectIsAuthenticated(state), composedComponent: ComposedComponent, }); }; return connect(mapStateToProps)(AuthenticatedComponent); }

Prueba de ejemplo:

 import React from 'react'; import { shallow, mount } from 'enzyme'; import { Provider } from 'react-redux'; import configureStore from 'redux-mock-store'; import RequireAuth, { AuthenticatedComponent } from '../'; const Component = () => <div />; Component.displayName = 'CustomComponent'; const mockStore = configureStore([]); describe.only('HOC', () => { const RequireAuthComponent = RequireAuth(Component); const context = { router: { push: jest.fn() } }; const wrapper = mount( <Provider store={mockStore({})}> <RequireAuthComponent /> </Provider>, { context, childContextTypes: { router: React.PropTypes.object.isRequired }, } ); it('should return a component', () => { expect(wrapper.find('Connect(AuthenticatedComponent)')).toHaveLength(1); }); it('should pass correct props', () => { expect(wrapper.find('AuthenticatedComponent').props()).toEqual( expect.objectContaining({ authenticated: false, composedComponent: Component, }) ); }); }); describe('rendering', () => { describe('is authenticated', () => { const wrapper = shallow( <AuthenticatedComponent composedComponent={Component} authenticated />, { context: { router: { push: jest.fn() } } } ); it('should render the passed component', () => { expect(wrapper.find('CustomComponent')).toHaveLength(1); }); }); describe('is not authenticated', () => { const wrapper = shallow( <AuthenticatedComponent composedComponent={Component} authenticated={false} />, { context: { router: { push: jest.fn() } } } ); it('should not render the passed component', () => { expect(wrapper.find('CustomComponent')).toHaveLength(0); }); }); });
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!