How to mock useSearchParams() and pass Query Parameter [NextJS routing]? #28255
-
I have a component called import { useSearchParams } from "next/navigation"
// Previous code
export const AttributeDescriptionModal = (props: AttributeDescriptionModalProps) => {
const contentRef = useRef<HTMLDivElement>(null)
const searchParams = useSearchParams()
const modernizationQueryParam = searchParams.get("status") // This throws error in the testing
const { close, isOpen, title, selectedAttribute } = props
const isCurrentModernization = modernizationQueryParam === "current"
// More code I want to write a component testing , but I blocked to mock Modal.cy.tsx describe("Description Attribute Modal Testing", () => {
const AttributeDescriptionModalComponent = () => {
const [isOpen, setIsOpen] = useState(true)
const basementInsulationList = currentBasementInsulationOptions.map(({ group }) => group)
const selectedAttribute = {
name: "Kellerdeckendämmung",
description: BASEMENT_INSULATION_DESCRIPTION,
options: basementInsulationList,
}
const [attribute, setAttribute] = useState<Attribute>(selectedAttribute)
const closeModal = () => {
setAttribute(attribute)
setIsOpen(false)
}
return (
<AttributeDescriptionModal
title='Attribute Description Modal Testing'
isOpen={isOpen}
selectedAttribute='Kellerdeckendämmung'
close={closeModal}
/>
)
}
const Modal = (
<MockNextRouter>
<Provider store={store}>
<AttributeDescriptionModalComponent />
</Provider>
</MockNextRouter>
)
it("Should render a description attribute Modal", () => {
cy.mount(Modal)
cy.get("[data-cy='core-modal']").should("exist")
cy.get("[data-cy='core-modal']").find("[data-cy=core-title]").contains("Attribute Description Modal Testing")
cy.get("[data-cy='core-modal']").find("[data-cy=core-title]").contains("Kellerdeckendämmung")
})
}) My Next Router mock based on next navigation mock: import { AppRouterContext, AppRouterInstance } from "next/dist/shared/lib/app-router-context"
const createNextRouter = (params: Partial<AppRouterInstance>) => ({
back: cy.spy().as("back"),
forward: cy.spy().as("forward"),
prefetch: cy.stub().as("prefetch").resolves(),
push: cy.spy().as("push"),
replace: cy.spy().as("replace"),
refresh: cy.spy().as("refresh"),
...params,
})
interface MockNextRouterProps extends Partial<AppRouterInstance> {
children: React.ReactNode
}
export const MockNextRouter = ({ children, ...props }: MockNextRouterProps) => {
const router = createNextRouter(props as AppRouterInstance)
return <AppRouterContext.Provider value={router}>{children}</AppRouterContext.Provider>
} When I run the test , I still have the same issue: See line 1524 |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 3 replies
-
did you find a solution? |
Beta Was this translation helpful? Give feedback.
-
You need to wrap your component with
|
Beta Was this translation helpful? Give feedback.
You need to wrap your component with
SearchParamsContext
, as you did withAppRouterContext
:Something like that: