I'm working on a React components library, and I need to add component testing. For this, I'm using Cypress. Most tests work well, except tests for components that I extend later with Styled components. On these ones, I get this error:
(uncaught exception)ReferenceError: Cannot access '<Component>' before initialization
On the components where I extend these first ones, the tests are working. What did I do wrong?
This is my code:
First component, the one where I get the error:
const StyledFlexbox = styled.div`
...styles
`
export function Flexbox(props) {
return <StyledFlexbox {...props} />
}
Second component, where I extend it:
import { Flexbox } from "../Flexbox"
const StyledSkeletonCard = styled(Flexbox)`
...styles
`
And the test for Flexbox component:
describe("<Flexbox />", () => {
it("renders <Flexbox /> component", () => {
cy.mount(
<Flexbox data-testid="testid">
Hello
</Flexbox>
)
cy.get('[data-testid="testid"]').should("exist")
})
})
Which returns:
(uncaught exception)ReferenceError: Cannot access 'Flexbox' before initialization
Also, when I use any of these components inside my app they work well, and I do not get any error. Thanks for your answers!
The problem is you created dependencies between components by sourcing cssVariables
from /lib/index.ts
. When you access that from the component test, all the other import/export components that are part of lib
are initiated as well.
I haven't tried to untangle the dependencies (it's a big job), but the easy fix is to also source the Flexbox
component from /lib/index.ts
.
// import { Flexbox } from "../Flexbox" // not this import!
import { cssVariables, Flexbox } from "../../.."
If I were you I would try to decouple the components, see Why Are SOLID Principles Vital...
Tight coupling means a group of classes are dependent on one another which should be avoided for better maintainability and readability of the code.