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

1.2K
Views
¿Por qué getComputedStyle() en una prueba JEST devuelve resultados diferentes a los estilos calculados en Chrome/Firefox DevTools?

He escrito un botón personalizado ( MyStyledButton ) basado en material-ui Button .

 import React from "react"; import { Button } from "@material-ui/core"; import { makeStyles } from "@material-ui/styles"; const useStyles = makeStyles({ root: { minWidth: 100 } }); function MyStyledButton(props) { const buttonStyle = useStyles(props); const { children, width, ...others } = props; return ( <Button classes={{ root: buttonStyle.root }} {...others}> {children} </Button> ); } export default MyStyledButton;

Tiene un estilo usando un tema y esto especifica que el color de backgroundColor sea un tono de amarillo (específicamente #fbb900 )

 import { createMuiTheme } from "@material-ui/core/styles"; export const myYellow = "#FBB900"; export const theme = createMuiTheme({ overrides: { MuiButton: { containedPrimary: { color: "black", backgroundColor: myYellow } } } });

El componente se instancia en mi index.js principal y se envuelve en el theme .

 <MuiThemeProvider theme={theme}> <MyStyledButton variant="contained" color="primary"> Primary Click Me </MyStyledButton> </MuiThemeProvider>

Si examino el botón en Chrome DevTools, el background-color se "calcula" como se esperaba. Este también es el caso en Firefox DevTools.

Captura de pantalla de Chrome

Sin embargo, cuando escribo una prueba JEST para verificar el background-color y consulto el estilo del nodo DOM del botón usando getComputedStyles() , obtengo una respuesta transparent y la prueba falla.

 const wrapper = mount( <MyStyledButton variant="contained" color="primary"> Primary </MyStyledButton> ); const foundButton = wrapper.find("button"); expect(foundButton).toHaveLength(1); //I want to check the background colour of the button here //I've tried getComputedStyle() but it returns 'transparent' instead of #FBB900 expect( window .getComputedStyle(foundButton.getDOMNode()) .getPropertyValue("background-color") ).toEqual(myYellow);

Incluí un CodeSandbox con el problema exacto, el código mínimo para reproducir y la prueba JEST fallida.

Editar headless-snow-nyofd

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Me he acercado, pero aún no he llegado a una solución.

El problema principal es que MUIButton inyecta una etiqueta al elemento para potenciar los estilos. Esto no está sucediendo en su prueba unitaria. Pude hacer que esto funcionara usando el createMount que usan las pruebas de materiales.

Después de esta solución, el estilo se muestra correctamente. Sin embargo, el estilo calculado todavía no funciona. Parece que otros han tenido problemas con la enzima que maneja esto correctamente, por lo que no estoy seguro de si es posible.

Para llegar a donde estaba, tome su fragmento de prueba, cópielo en la parte superior y luego cambie su código de prueba a:

 const myMount = createMount({ strict: true }); const wrapper = myMount( <MuiThemeProvider theme={theme}> <MyStyledButton variant="contained" color="primary"> Primary </MyStyledButton> </MuiThemeProvider> );
 class Mode extends React.Component { static propTypes = { /** * this is essentially children. However we can't use children because then * using `wrapper.setProps({ children })` would work differently if this component * would be the root. */ __element: PropTypes.element.isRequired, __strict: PropTypes.bool.isRequired, }; render() { // Excess props will come from eg enzyme setProps const { __element, __strict, ...other } = this.props; const Component = __strict ? React.StrictMode : React.Fragment; return <Component>{React.cloneElement(__element, other)}</Component>; } } // Generate an enhanced mount function. function createMount(options = {}) { const attachTo = document.createElement('div'); attachTo.className = 'app'; attachTo.setAttribute('id', 'app'); document.body.insertBefore(attachTo, document.body.firstChild); const mountWithContext = function mountWithContext(node, localOptions = {}) { const strict = true; const disableUnnmount = false; const localEnzymeOptions = {}; const globalEnzymeOptions = {}; if (!disableUnnmount) { ReactDOM.unmountComponentAtNode(attachTo); } // some tests require that no other components are in the tree // eg when doing .instance(), .state() etc. return mount(strict == null ? node : <Mode __element={node} __strict={Boolean(strict)} />, { attachTo, ...globalEnzymeOptions, ...localEnzymeOptions, }); }; mountWithContext.attachTo = attachTo; mountWithContext.cleanUp = () => { ReactDOM.unmountComponentAtNode(attachTo); attachTo.parentElement.removeChild(attachTo); }; return mountWithContext; }
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!