From 68d26ab8df6fb34e6c89518c0f654d4ea40bd437 Mon Sep 17 00:00:00 2001 From: jzunigax2 <125698953+jzunigax2@users.noreply.github.com> Date: Thu, 3 Dec 2026 15:22:24 -0600 Subject: [PATCH] chore: add testing utilities and LoginPageView tests - Introduced testing utilities for rendering components with context providers. - Added comprehensive tests for the LoginPageView component, covering form validation, authentication flow, and error handling. - Updated package dependencies to include Testing Library packages for improved testing capabilities. - Configured testing environment setup for consistent test execution. --- package-lock.json | 245 +++++++++++++++++++++ package.json | 4 + src/components/auth/LoginPageView.test.tsx | 190 ++++++++++++++++ src/testing/api-error.ts | 12 + src/testing/render.tsx | 131 +++++++++++ src/testing/setup.ts | 8 + vite.config.ts | 1 + 7 files changed, 591 insertions(+) create mode 100644 src/components/auth/LoginPageView.test.tsx create mode 100644 src/testing/api-error.ts create mode 100644 src/testing/render.tsx create mode 100644 src/testing/setup.ts diff --git a/package-lock.json b/package-lock.json index c0fe735b..84e650b3 100644 --- a/package-lock.json +++ b/package-lock.json @@ -38,6 +38,10 @@ "@internxt/css-config": "^1.2.0", "@internxt/eslint-config-internxt": "^2.1.2", "@internxt/prettier-config": "^2.0.1", + "@testing-library/dom": "^10.4.2", + "@testing-library/jest-dom": "^8.0.0", + "@testing-library/react": "^16.3.3", + "@testing-library/user-event": "^14.6.14", "@types/react": "^19.2.17", "@types/react-date-range": "^1.4.10", "@types/react-dom": "^19.2.3", @@ -62,6 +66,13 @@ "node": ">=24" } }, + "node_modules/@adobe/css-tools": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/@adobe/css-tools/-/css-tools-4.5.0.tgz", + "integrity": "sha512-6OzddxPio9UiWTCemp4N8cYLV2ZN1ncRnV1cVGtve7dhPOtRkleRyx32GQCYSwDYgaHU3USMm84tNsvKzRCa1Q==", + "dev": true, + "license": "MIT" + }, "node_modules/@alloc/quick-lru": { "version": "5.2.0", "resolved": "https://registry.npmjs.org/@alloc/quick-lru/-/quick-lru-5.2.0.tgz", @@ -2389,6 +2400,111 @@ "node": ">=14.0.0" } }, + "node_modules/@testing-library/dom": { + "version": "10.4.2", + "resolved": "https://registry.npmjs.org/@testing-library/dom/-/dom-10.4.2.tgz", + "integrity": "sha512-yzr2S9HyAIdhz2/6qHgbs665Q7PKVcDF05vsOlHPxG1mo36gKVesdYVeDLnXgfjJ03CrKRk08knc6+E/9m8v2Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.10.4", + "@babel/runtime": "^7.12.5", + "@types/aria-query": "^5.0.1", + "aria-query": "5.3.0", + "dom-accessibility-api": "^0.5.9", + "lz-string": "^1.5.0", + "picocolors": "1.1.1", + "pretty-format": "^27.0.2" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@testing-library/jest-dom": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/@testing-library/jest-dom/-/jest-dom-8.0.0.tgz", + "integrity": "sha512-Nu45KEeFgP/ydCMipnisMblq6YHViqEFi3fKN0a40s+zdKDDD7vEPCEavS0i7i4RxmclcEIL8q2o42pu+WgNgg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@adobe/css-tools": "^4.4.0", + "aria-query": "^5.0.0", + "css.escape": "^1.5.1", + "dom-accessibility-api": "^0.6.3", + "picocolors": "^1.1.1", + "redent": "^3.0.0" + }, + "engines": { + "node": ">=22", + "npm": ">=6", + "yarn": ">=1" + }, + "peerDependencies": { + "@testing-library/dom": ">=10 <11", + "vitest": ">=5 <6" + }, + "peerDependenciesMeta": { + "vitest": { + "optional": true + } + } + }, + "node_modules/@testing-library/jest-dom/node_modules/dom-accessibility-api": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/dom-accessibility-api/-/dom-accessibility-api-0.6.3.tgz", + "integrity": "sha512-7ZgogeTnjuHbo+ct10G9Ffp0mif17idi0IyWNVA/wcwcm7NPOD/WEHVP3n7n3MhXqxoIYm8d6MuZohYWIZ4T3w==", + "dev": true, + "license": "MIT" + }, + "node_modules/@testing-library/react": { + "version": "16.3.3", + "resolved": "https://registry.npmjs.org/@testing-library/react/-/react-16.3.3.tgz", + "integrity": "sha512-Uo193NgQbPMz6lrrhtRQQFcMC6Re/ELLFbbuVL30WDlZxlpZf9/lMHTAVxPRLw1q1iu9OJmR1c2BLiENRstdBg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.12.5" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@testing-library/dom": "^10.0.0", + "@types/react": "^18.0.0 || ^19.0.0", + "@types/react-dom": "^18.0.0 || ^19.0.0", + "react": "^18.0.0 || ^19.0.0", + "react-dom": "^18.0.0 || ^19.0.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@testing-library/user-event": { + "version": "14.6.14", + "resolved": "https://registry.npmjs.org/@testing-library/user-event/-/user-event-14.6.14.tgz", + "integrity": "sha512-N2IuJHrFLa4uEpVzOqMjwoFJ26PLjbEZnX+8ogaDKRcKyKGb5WviZW4IZ1zOQZJzIZGpB0ESkG4QTjJ4ViiYtA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12", + "npm": ">=6" + }, + "peerDependencies": { + "@testing-library/dom": ">=7.21.4" + } + }, + "node_modules/@types/aria-query": { + "version": "5.0.4", + "resolved": "https://registry.npmjs.org/@types/aria-query/-/aria-query-5.0.4.tgz", + "integrity": "sha512-rfT93uj5s0PRL7EzccGMs3brplhcrghnDoV26NqKhCAS1hVo+WdNsPvE/yb6ilfr5hi2MEk6d5EWJTKdxg8jVw==", + "dev": true, + "license": "MIT" + }, "node_modules/@types/babel__core": { "version": "7.20.5", "resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz", @@ -3253,6 +3369,29 @@ "url": "https://github.com/sponsors/epoberezkin" } }, + "node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/ansi-styles": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-5.2.0.tgz", + "integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, "node_modules/any-promise": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/any-promise/-/any-promise-1.3.0.tgz", @@ -3281,6 +3420,16 @@ "dev": true, "license": "MIT" }, + "node_modules/aria-query": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/aria-query/-/aria-query-5.3.0.tgz", + "integrity": "sha512-b0P0sZPKtyu8HkeRAfCq0IfURZK+SuwMjY1UXGBU27wpAiTwQAIlq56IbIO+ytk/JjS1fMR14ee5WBBfKi5J6A==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "dequal": "^2.0.3" + } + }, "node_modules/assertion-error": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz", @@ -3714,6 +3863,13 @@ "node": "^10 || ^12.20.0 || ^14.13.0 || >=15.0.0" } }, + "node_modules/css.escape": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/css.escape/-/css.escape-1.5.1.tgz", + "integrity": "sha512-YUifsXXuknHlUsmlgyY0PKzgPOr7/FjCePfHNt0jxm83wHZi44VDMQ7/fGNkjY3/jV1MC+1CmZbaHzugyeRtpg==", + "dev": true, + "license": "MIT" + }, "node_modules/cssesc": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/cssesc/-/cssesc-3.0.0.tgz", @@ -3930,6 +4086,16 @@ "node": ">=0.4.0" } }, + "node_modules/dequal": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz", + "integrity": "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, "node_modules/diacritics": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/diacritics/-/diacritics-1.3.0.tgz", @@ -3950,6 +4116,13 @@ "dev": true, "license": "MIT" }, + "node_modules/dom-accessibility-api": { + "version": "0.5.16", + "resolved": "https://registry.npmjs.org/dom-accessibility-api/-/dom-accessibility-api-0.5.16.tgz", + "integrity": "sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg==", + "dev": true, + "license": "MIT" + }, "node_modules/dom-helpers": { "version": "5.2.1", "resolved": "https://registry.npmjs.org/dom-helpers/-/dom-helpers-5.2.1.tgz", @@ -4891,6 +5064,16 @@ "node": ">=0.8.19" } }, + "node_modules/indent-string": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/indent-string/-/indent-string-4.0.0.tgz", + "integrity": "sha512-EdDDZu4A2OyIK7Lr/2zG+w5jmbuk1DVBnEwREQvBzspBJkCEbRa8GxU1lghYcaGJCnRWibjDXlq779X1/y5xwg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, "node_modules/inherits": { "version": "2.0.4", "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", @@ -5209,6 +5392,16 @@ "react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, + "node_modules/lz-string": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/lz-string/-/lz-string-1.5.0.tgz", + "integrity": "sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ==", + "dev": true, + "license": "MIT", + "bin": { + "lz-string": "bin/bin.js" + } + }, "node_modules/magicast": { "version": "0.5.5", "resolved": "https://registry.npmjs.org/magicast/-/magicast-0.5.5.tgz", @@ -5282,6 +5475,16 @@ "node": ">= 0.6" } }, + "node_modules/min-indent": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/min-indent/-/min-indent-1.0.1.tgz", + "integrity": "sha512-I9jwMn07Sy/IwOj3zVkVik2JTvgpaykDZEigL6Rx6N9LbMywwUSMtxET+7lVoDLLd3O3IXwJwvuuns8UB/HeAg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, "node_modules/minimatch": { "version": "10.2.6", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.6.tgz", @@ -5732,6 +5935,21 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/pretty-format": { + "version": "27.5.1", + "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-27.5.1.tgz", + "integrity": "sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1", + "ansi-styles": "^5.0.0", + "react-is": "^17.0.1" + }, + "engines": { + "node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0" + } + }, "node_modules/prop-types": { "version": "15.8.1", "resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.8.1.tgz", @@ -6072,6 +6290,20 @@ "decimal.js-light": "^2.4.1" } }, + "node_modules/redent": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/redent/-/redent-3.0.0.tgz", + "integrity": "sha512-6tDA8g98We0zd0GvVeMT9arEOnTw9qM03L9cJXaCjrip1OO764RDBLBfrB4cwzNGDj5OA5ioymC9GkizgWJDUg==", + "dev": true, + "license": "MIT", + "dependencies": { + "indent-string": "^4.0.0", + "strip-indent": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/require-from-string": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", @@ -6326,6 +6558,19 @@ "node": ">=0.6.19" } }, + "node_modules/strip-indent": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/strip-indent/-/strip-indent-3.0.0.tgz", + "integrity": "sha512-laJTa3Jb+VQpaC6DseHhF7dXVqHTfJPCRDaEbid/drOhgitgYku/letMUqOXFoWV0zIIUbjpdH2t+tYj4bQMRQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "min-indent": "^1.0.0" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/sucrase": { "version": "3.35.1", "resolved": "https://registry.npmjs.org/sucrase/-/sucrase-3.35.1.tgz", diff --git a/package.json b/package.json index 5ff0e5cc..8b6d3432 100644 --- a/package.json +++ b/package.json @@ -47,6 +47,10 @@ "@internxt/css-config": "^1.2.0", "@internxt/eslint-config-internxt": "^2.1.2", "@internxt/prettier-config": "^2.0.1", + "@testing-library/dom": "^10.4.2", + "@testing-library/jest-dom": "^8.0.0", + "@testing-library/react": "^16.3.3", + "@testing-library/user-event": "^14.6.14", "@types/react": "^19.2.17", "@types/react-date-range": "^1.4.10", "@types/react-dom": "^19.2.3", diff --git a/src/components/auth/LoginPageView.test.tsx b/src/components/auth/LoginPageView.test.tsx new file mode 100644 index 00000000..ae5a6afb --- /dev/null +++ b/src/components/auth/LoginPageView.test.tsx @@ -0,0 +1,190 @@ +import { ComponentProps } from 'react'; +import { screen } from '@testing-library/react'; +import dayjs from 'dayjs'; +import { describe, expect, test, vi } from 'vitest'; +import { LoginPageView } from './LoginPageView'; +import { renderWithProviders } from '../../testing/render'; +import { apiError } from '../../testing/api-error'; +import { CaptchaUnavailableError } from '../../services/captcha.service'; + +type Props = ComponentProps; + +function renderLogin(props: Partial = {}, route = '/login') { + const logIn = props.logIn ?? vi.fn().mockResolvedValue(undefined); + const result = renderWithProviders( + , + { + route, + path: '/login', + routes: { '/home':

home page

, '/elsewhere':

elsewhere page

}, + }, + ); + return { ...result, logIn }; +} + +const logInButton = () => screen.getByRole('button', { name: 'Log in' }); + +async function submitCredentials(user: ReturnType['user']) { + await user.type(screen.getByPlaceholderText('Email'), 'user@internxt.com'); + await user.type(screen.getByPlaceholderText('Password'), 'secret'); + await user.click(logInButton()); +} + +describe('LoginPageView', () => { + describe('form', () => { + test('when email or password is empty, then Log in is disabled', async () => { + const { user } = renderLogin(); + + expect(logInButton()).toBeDisabled(); + await user.type(screen.getByPlaceholderText('Email'), 'user@internxt.com'); + expect(logInButton()).toBeDisabled(); + await user.type(screen.getByPlaceholderText('Password'), 'secret'); + expect(logInButton()).toBeEnabled(); + }); + + test('when the credentials are accepted, then it logs in without a code and goes to redirectTo', async () => { + const { user, logIn } = renderLogin(); + + await submitCredentials(user); + + expect(logIn).toHaveBeenCalledWith('user@internxt.com', 'secret', undefined); + expect(await screen.findByText('home page')).toBeInTheDocument(); + }); + }); + + describe('redirects', () => { + test('when the user is already authenticated, then it redirects straight away', async () => { + renderLogin({ isAuthenticated: true }); + + expect(await screen.findByText('home page')).toBeInTheDocument(); + }); + + test('when ?redirect= is an internal path, then it goes there after logging in', async () => { + const { user } = renderLogin({}, '/login?redirect=/elsewhere'); + + await submitCredentials(user); + + expect(await screen.findByText('elsewhere page')).toBeInTheDocument(); + }); + + test.each(['//evil.com/elsewhere', '/\\evil.com', 'https://evil.com'])( + 'when ?redirect=%s points off-site, then it is ignored in favour of redirectTo', + async (redirect) => { + const { user } = renderLogin({}, `/login?redirect=${encodeURIComponent(redirect)}`); + + await submitCredentials(user); + + expect(await screen.findByText('home page')).toBeInTheDocument(); + }, + ); + }); + + describe('errors', () => { + test('when the credentials are rejected, then it shows the invalid-credentials message and stays on the page', async () => { + const { user } = renderLogin({ logIn: vi.fn().mockRejectedValue(apiError(401)) }); + + await submitCredentials(user); + + expect(await screen.findByText('Invalid credentials')).toBeInTheDocument(); + expect(screen.queryByText('home page')).not.toBeInTheDocument(); + }); + + test('when the console maps the error, then its message is shown instead', async () => { + const { user } = renderLogin({ + logIn: vi.fn().mockRejectedValue(apiError(403, { code: 'SSO_REQUIRED' })), + mapLoginError: () => 'Use single sign-on', + }); + + await submitCredentials(user); + + expect(await screen.findByText('Use single sign-on')).toBeInTheDocument(); + }); + + test('when the captcha could not be loaded, then it asks the user to disable their ad blocker', async () => { + const { user } = renderLogin({ logIn: vi.fn().mockRejectedValue(new CaptchaUnavailableError()) }); + + await submitCredentials(user); + + expect( + await screen.findByText('Verification could not be loaded. Disable your ad blocker and try again.'), + ).toBeInTheDocument(); + }); + + test('when the account is locked, then it shows until when', async () => { + const lockedUntil = '2026-12-03T18:45:00.000Z'; + const { user } = renderLogin({ + logIn: vi.fn().mockRejectedValue(apiError(403, { code: 'ACCOUNT_LOCKED', lockedUntil })), + }); + + await submitCredentials(user); + + const time = dayjs(lockedUntil).format('HH:mm'); + expect( + await screen.findByText(`Too many failed attempts. Your account is locked until ${time}.`), + ).toBeInTheDocument(); + }); + + test('when the account is locked and the console has password reset, then it also suggests resetting', async () => { + const lockedUntil = '2026-12-03T18:45:00.000Z'; + const { user } = renderLogin({ + logIn: vi.fn().mockRejectedValue(apiError(403, { code: 'ACCOUNT_LOCKED', lockedUntil })), + forgotPasswordPath: '/forgot-password', + }); + + await submitCredentials(user); + + expect(await screen.findByText(/You can also reset your password\.$/)).toBeInTheDocument(); + expect(screen.getByRole('link', { name: 'Forgot password?' })).toHaveAttribute('href', '/forgot-password'); + }); + }); + + describe('two-factor step', () => { + const twoFactorRequired = () => apiError(403, { message: '2FA_REQUIRED' }); + + test('when the server asks for 2FA, then it shows the code field and only enables Verify for 6 digits', async () => { + const logIn = vi.fn().mockRejectedValueOnce(twoFactorRequired()).mockResolvedValueOnce(undefined); + const { user } = renderLogin({ logIn, supportsTwoFactor: true }); + + await submitCredentials(user); + + const codeInput = await screen.findByPlaceholderText('6-digit code'); + const verify = screen.getByRole('button', { name: 'Verify' }); + expect(screen.queryByText('Invalid credentials')).not.toBeInTheDocument(); + expect(verify).toBeDisabled(); + + await user.type(codeInput, '12345'); + expect(verify).toBeDisabled(); + await user.type(codeInput, '6'); + expect(verify).toBeEnabled(); + + await user.click(verify); + + expect(logIn).toHaveBeenLastCalledWith('user@internxt.com', 'secret', '123456'); + expect(await screen.findByText('home page')).toBeInTheDocument(); + }); + + test('when the code is wrong, then it shows the invalid-code message and keeps the code step', async () => { + const logIn = vi + .fn() + .mockRejectedValueOnce(twoFactorRequired()) + .mockRejectedValueOnce(apiError(401, { message: 'Invalid two-factor code' })); + const { user } = renderLogin({ logIn, supportsTwoFactor: true }); + + await submitCredentials(user); + await user.type(await screen.findByPlaceholderText('6-digit code'), '000000'); + await user.click(screen.getByRole('button', { name: 'Verify' })); + + expect(await screen.findByText('Invalid code')).toBeInTheDocument(); + expect(screen.getByPlaceholderText('6-digit code')).toBeInTheDocument(); + }); + + test('when the console does not support 2FA, then a 2FA_REQUIRED answer is shown as invalid credentials', async () => { + const { user } = renderLogin({ logIn: vi.fn().mockRejectedValue(twoFactorRequired()) }); + + await submitCredentials(user); + + expect(await screen.findByText('Invalid credentials')).toBeInTheDocument(); + expect(screen.queryByPlaceholderText('6-digit code')).not.toBeInTheDocument(); + }); + }); +}); diff --git a/src/testing/api-error.ts b/src/testing/api-error.ts new file mode 100644 index 00000000..7cf246b7 --- /dev/null +++ b/src/testing/api-error.ts @@ -0,0 +1,12 @@ +import { AxiosError, AxiosHeaders, InternalAxiosRequestConfig } from 'axios'; + +export function apiError(status: number, data: unknown = {}): AxiosError { + const config = { headers: new AxiosHeaders() } as InternalAxiosRequestConfig; + return new AxiosError(`Request failed with status code ${status}`, undefined, config, undefined, { + status, + statusText: '', + data, + headers: {}, + config, + }); +} diff --git a/src/testing/render.tsx b/src/testing/render.tsx new file mode 100644 index 00000000..6e40b7de --- /dev/null +++ b/src/testing/render.tsx @@ -0,0 +1,131 @@ +import { ReactElement, ReactNode } from 'react'; +import { render, RenderOptions } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { MemoryRouter, Route, Routes } from 'react-router-dom'; +import { vi } from 'vitest'; +import '../i18n'; +import { ManagementContext, ManagementContextType } from '../management/context/useManagement'; +import { PartnersContext, PartnersContextType } from '../partners/context/usePartners'; +import { WholesalersContext, WholesalersContextType } from '../wholesalers/context/useWholesalers'; +import { SubAccountContext, SubAccountContextType } from '../sub-account/context/useSubAccount'; +import { SubAccountBrandingContext } from '../sub-account/context/SubAccountBrandingContext'; +import { + BrandingStyles, + DEFAULT_BRANDING, + SubAccountBrandingContextValue, +} from '../sub-account/context/SubAccountBrandingContext/constants'; + +export interface ProvidersOptions { + route?: string; + path?: string; + routes?: Record; + management?: Partial; + partners?: Partial; + wholesalers?: Partial; + subAccount?: Partial; + branding?: Partial; +} + +export const fakeManagement = (overrides: Partial = {}): ManagementContextType => ({ + isAuthenticated: false, + isOwner: false, + me: null, + isMeLoading: false, + twoFactorSetupRequired: false, + clearTwoFactorSetupRequired: vi.fn(), + logIn: vi.fn().mockResolvedValue(undefined), + logOut: vi.fn(), + ...overrides, +}); + +export const fakePartners = (overrides: Partial = {}): PartnersContextType => ({ + isAuthenticated: false, + isViewer: false, + partnerInfo: null, + twoFactorSetupRequired: false, + clearTwoFactorSetupRequired: vi.fn(), + logIn: vi.fn().mockResolvedValue(undefined), + logOut: vi.fn(), + ...overrides, +}); + +export const fakeWholesalers = (overrides: Partial = {}): WholesalersContextType => ({ + isAuthenticated: false, + isViewer: false, + wholesalerEmail: null, + twoFactorSetupRequired: false, + clearTwoFactorSetupRequired: vi.fn(), + logIn: vi.fn().mockResolvedValue(undefined), + logOut: vi.fn(), + ...overrides, +}); + +export const fakeSubAccount = (overrides: Partial = {}): SubAccountContextType => ({ + isAuthenticated: false, + isAdmin: false, + ssoEnabled: false, + auditLogEnabled: false, + memberId: null, + entityId: null, + partnerId: null, + entityCreatedAt: null, + email: null, + logIn: vi.fn().mockResolvedValue(undefined), + logInWithSso: vi.fn().mockResolvedValue(undefined), + refreshClaims: vi.fn(), + logOut: vi.fn(), + ...overrides, +}); + +export const fakeBranding = ( + overrides: Partial = {}, +): SubAccountBrandingContextValue => ({ + branding: DEFAULT_BRANDING, + styles: {} as BrandingStyles, + isLoading: false, + ...overrides, +}); + +function buildWrapper(options: ProvidersOptions) { + const { path = '*', routes = {}, management, partners, wholesalers, subAccount, branding } = options; + const route = options.route ?? (path === '*' ? '/' : path); + + return function Providers({ children }: { children: ReactNode }) { + let tree: ReactNode = ( + + + + {Object.entries(routes).map(([routePath, element]) => ( + + ))} + + + ); + + tree = ( + {tree} + ); + if (subAccount) + tree = {tree}; + if (wholesalers) { + tree = {tree}; + } + if (partners) tree = {tree}; + if (management) { + tree = {tree}; + } + return <>{tree}; + }; +} + +/** + * Renders `ui` inside a MemoryRouter, the app's i18n instance, branding and whichever console + * contexts the test overrides (with `vi.fn()` defaults for everything not overridden). + * Returns RTL's result plus a `user` from `userEvent.setup()`. + */ +export function renderWithProviders(ui: ReactElement, options: ProvidersOptions & Omit = {}) { + const { route, path, routes, management, partners, wholesalers, subAccount, branding, ...renderOptions } = options; + const user = userEvent.setup(); + const wrapper = buildWrapper({ route, path, routes, management, partners, wholesalers, subAccount, branding }); + return { user, ...render(ui, { wrapper, ...renderOptions }) }; +} diff --git a/src/testing/setup.ts b/src/testing/setup.ts new file mode 100644 index 00000000..6c1577b0 --- /dev/null +++ b/src/testing/setup.ts @@ -0,0 +1,8 @@ +import '@testing-library/jest-dom/vitest'; +import { cleanup } from '@testing-library/react'; +import { afterEach } from 'vitest'; + +afterEach(() => { + cleanup(); + localStorage.clear(); +}); diff --git a/vite.config.ts b/vite.config.ts index 6dbe9f4e..b70c8df2 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -9,6 +9,7 @@ export default defineConfig({ }, test: { environment: 'jsdom', + setupFiles: ['./src/testing/setup.ts'], coverage: { provider: 'istanbul', reporter: ['text', 'html', 'lcov'],