From 0e16429b0d8af8d65040c06af3b895f4e10b310a Mon Sep 17 00:00:00 2001 From: Sean Cassiere <33615041+SeanCassiere@users.noreply.github.com> Date: Mon, 9 Sep 2024 13:38:48 +1200 Subject: [PATCH] test(react-router): `onEnter` should have the router context defined (#2295) * test(react-router): `onEnter` should have the router context defined * test(react-router): remove the `waitFor` call --- packages/react-router/tests/route.test.tsx | 65 ++++++++++++++++++++-- 1 file changed, 60 insertions(+), 5 deletions(-) diff --git a/packages/react-router/tests/route.test.tsx b/packages/react-router/tests/route.test.tsx index a5a9a018b2..e09642ba35 100644 --- a/packages/react-router/tests/route.test.tsx +++ b/packages/react-router/tests/route.test.tsx @@ -1,13 +1,21 @@ -/* eslint-disable */ -import { describe, it, expect } from 'vitest' +import React from 'react' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { cleanup, render, screen } from '@testing-library/react' + import { - getRouteApi, - createRoute, + RouterProvider, createRootRoute, + createRoute, createRouter, + getRouteApi, useNavigate, } from '../src' -import React from 'react' + +afterEach(() => { + vi.resetAllMocks() + window.history.replaceState(null, 'root', '/') + cleanup() +}) describe('getRouteApi', () => { it('should have the useMatch hook', () => { @@ -139,3 +147,50 @@ describe('throws invariant exception when trying to access properties before `cr }) }) */ + +describe('onEnter event', () => { + it('should have router context defined in router.load()', async () => { + const fn = vi.fn() + const rootRoute = createRootRoute() + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () => { + return

Index

+ }, + onEnter: ({ context }) => { + fn(context) + }, + }) + const routeTree = rootRoute.addChildren([indexRoute]) + const router = createRouter({ routeTree, context: { foo: 'bar' } }) + + await router.load() + + expect(fn).toHaveBeenCalledWith({ foo: 'bar' }) + }) + + it('should have router context defined in ', async () => { + const fn = vi.fn() + const rootRoute = createRootRoute() + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () => { + return

Index

+ }, + onEnter: ({ context }) => { + fn(context) + }, + }) + const routeTree = rootRoute.addChildren([indexRoute]) + const router = createRouter({ routeTree, context: { foo: 'bar' } }) + + render() + + const indexElem = await screen.findByText('Index') + expect(indexElem).toBeInTheDocument() + + expect(fn).toHaveBeenCalledWith({ foo: 'bar' }) + }) +})