level_0
int64
0
10k
index
int64
0
0
repo_id
stringlengths
22
152
file_path
stringlengths
41
203
content
stringlengths
11
11.5M
5,559
0
petrpan-code/redwoodjs/redwood/packages/internal/src
petrpan-code/redwoodjs/redwood/packages/internal/src/__tests__/routes-mocked.test.ts
jest.mock('@redwoodjs/project-config', () => ({ getPaths: () => ({ base: '', }), })) jest.mock('@redwoodjs/structure/dist/model/RWRoute', () => ({ RWRoute: {}, })) jest.mock('@redwoodjs/structure', () => { return { getProject: () => { return { router: { // <Router useAuth={useAuth}> // <Route path="/login" page={LoginPage} name="login" /> // <Route path="/" redirect="/dashboard" /> // <Route notfound page={NotFoundPage} /> // </Router> routes: [ { name: 'login', page_identifier_str: 'LoginPage', path: '/login', }, { path: '/', }, { page_identifier_str: 'NotFoundPage', }, ], }, } }, } }) import { getDuplicateRoutes, warningForDuplicateRoutes } from '../routes' describe('notfound and redirect routes', () => { it('Detects no duplicate routes', () => { expect(getDuplicateRoutes()).toStrictEqual([]) }) it('Produces the correct warning message', () => { expect(warningForDuplicateRoutes()).toBe('') }) })
5,560
0
petrpan-code/redwoodjs/redwood/packages/internal/src
petrpan-code/redwoodjs/redwood/packages/internal/src/__tests__/routes.test.ts
import path from 'path' import { getDuplicateRoutes, warningForDuplicateRoutes } from '../routes' const FIXTURE_PATH_EMPTY_PROJECT = path.resolve( __dirname, '../../../../__fixtures__/empty-project' ) const FIXTURE_PATH_EXAMPLE = path.resolve( __dirname, '../../../../__fixtures__/example-todo-main' ) const FIXTURE_PATH_EXAMPLE_WITH_ERRORS = path.resolve( __dirname, '../../../../__fixtures__/example-todo-main-with-errors' ) const FIXTURE_PATH_TEST_PROJECT = path.resolve( __dirname, '../../../../__fixtures__/test-project' ) describe('Routes within the empty project', () => { beforeAll(() => { process.env.RWJS_CWD = FIXTURE_PATH_EMPTY_PROJECT }) afterAll(() => { delete process.env.RWJS_CWD }) it('Detects no duplicate routes', () => { expect(getDuplicateRoutes()).toStrictEqual([]) }) it('Produces the correct warning message', () => { expect(warningForDuplicateRoutes()).toBe('') }) }) describe('Routes within the example todo project', () => { beforeAll(() => { process.env.RWJS_CWD = FIXTURE_PATH_EXAMPLE }) afterAll(() => { delete process.env.RWJS_CWD }) it('Detects no duplicate routes', () => { expect(getDuplicateRoutes()).toStrictEqual([]) }) it('Produces the correct warning message', () => { expect(warningForDuplicateRoutes()).toBe('') }) }) describe('Routes within the example todo with errors project', () => { beforeAll(() => { process.env.RWJS_CWD = FIXTURE_PATH_EXAMPLE_WITH_ERRORS }) afterAll(() => { delete process.env.RWJS_CWD }) it('Detects duplicate root routes', () => { expect(getDuplicateRoutes()).toStrictEqual([ { name: 'home', page: 'HomePage', path: '/' }, { name: 'home', page: 'HomePage', path: '/' }, ]) }) it('Produces the correct warning message', () => { expect(warningForDuplicateRoutes()).toMatch( /Warning: 2 duplicate routes have been detected, only the route\(s\) closest to the top of the file will be used.+\n.+Name: \"home\", Path: \"\/\", Page: \"HomePage\"\n.+Name: \"home\", Path: \"\/\", Page: \"HomePage\"/ ) }) }) describe('Routes within the test project', () => { beforeAll(() => { process.env.RWJS_CWD = FIXTURE_PATH_TEST_PROJECT }) afterAll(() => { delete process.env.RWJS_CWD }) it('Detects no duplicate routes', () => { expect(getDuplicateRoutes()).toStrictEqual([]) }) it('Produces the correct warning message', () => { expect(warningForDuplicateRoutes()).toBe('') }) })
5,561
0
petrpan-code/redwoodjs/redwood/packages/internal/src
petrpan-code/redwoodjs/redwood/packages/internal/src/__tests__/typeDefinitions.test.ts
import fs from 'fs' import path from 'path' import { ensurePosixPath } from '@redwoodjs/project-config' import { findCells, findDirectoryNamedModules } from '../files' import { generateMirrorCells, generateMirrorDirectoryNamedModules, generateTypeDefRouterPages, generateTypeDefCurrentUser, generateTypeDefRouterRoutes, generateTypeDefGlobImports, generateTypeDefGlobalContext, mirrorPathForDirectoryNamedModules, mirrorPathForCell, generateTypeDefScenarios, } from '../generate/typeDefinitions' const FIXTURE_PATH = path.resolve( __dirname, '../../../../__fixtures__/example-todo-main' ) beforeAll(() => { process.env.RWJS_CWD = FIXTURE_PATH }) afterAll(() => { delete process.env.RWJS_CWD }) const cleanPaths = (p) => { return ensurePosixPath(path.relative(FIXTURE_PATH, p)) } test('generate the correct mirror types for cells', () => { const paths = generateMirrorCells() const p = paths.map(cleanPaths) expect(p).toMatchInlineSnapshot(` [ ".redwood/types/mirror/web/src/components/NumTodosCell/index.d.ts", ".redwood/types/mirror/web/src/components/NumTodosTwoCell/index.d.ts", ".redwood/types/mirror/web/src/components/TodoListCell/index.d.ts", ] `) expect(fs.readFileSync(paths[0], 'utf-8')).toMatchInlineSnapshot(` "// This file was generated by RedwoodJS import * as Cell from './NumTodosCell' import type { CellProps } from '@redwoodjs/web' import type { NumTodosCell_GetCount, NumTodosCell_GetCountVariables } from 'types/graphql' type SuccessType = typeof Cell.Success export * from './NumTodosCell' type CellInputs = CellProps<SuccessType, NumTodosCell_GetCount, typeof Cell, NumTodosCell_GetCountVariables> export default function (props: CellInputs): ReturnType<SuccessType> //# sourceMappingURL=index.d.ts.map " `) }) test('generate the correct mirror types for directory named modules', () => { const paths = generateMirrorDirectoryNamedModules() const p = paths.map(cleanPaths) expect(p).toMatchInlineSnapshot(` [ ".redwood/types/mirror/web/src/graphql/index.d.ts", ".redwood/types/mirror/api/src/directives/requireAuth/index.d.ts", ".redwood/types/mirror/api/src/directives/skipAuth/index.d.ts", ".redwood/types/mirror/api/src/functions/healthz/index.d.ts", ".redwood/types/mirror/api/src/functions/nested/index.d.ts", ".redwood/types/mirror/api/src/services/todos/index.d.ts", ".redwood/types/mirror/web/src/components/AddTodo/index.d.ts", ".redwood/types/mirror/web/src/components/AddTodoControl/index.d.ts", ".redwood/types/mirror/web/src/components/Check/index.d.ts", ".redwood/types/mirror/web/src/components/TableCell/index.d.ts", ".redwood/types/mirror/web/src/components/TodoItem/index.d.ts", ".redwood/types/mirror/web/src/layouts/SetLayout/index.d.ts", ".redwood/types/mirror/web/src/pages/BarPage/index.d.ts", ".redwood/types/mirror/web/src/pages/FatalErrorPage/index.d.ts", ".redwood/types/mirror/web/src/pages/FooPage/index.d.ts", ".redwood/types/mirror/web/src/pages/HomePage/index.d.ts", ".redwood/types/mirror/web/src/pages/NotFoundPage/index.d.ts", ".redwood/types/mirror/web/src/pages/PrivatePage/index.d.ts", ".redwood/types/mirror/web/src/pages/TypeScriptPage/index.d.ts", ".redwood/types/mirror/web/src/pages/admin/EditUserPage/index.d.ts", ] `) expect(fs.readFileSync(paths[0], 'utf-8')).toMatchInlineSnapshot(` "// This file was generated by RedwoodJS import { default as DEFAULT } from './graphql' export default DEFAULT export * from './graphql' //# sourceMappingURL=index.d.ts.map " `) expect(fs.readFileSync(paths[0], 'utf-8')).toMatchInlineSnapshot(` "// This file was generated by RedwoodJS import { default as DEFAULT } from './graphql' export default DEFAULT export * from './graphql' //# sourceMappingURL=index.d.ts.map " `) }) test('generates global page imports', () => { const paths = generateTypeDefRouterPages() const p = paths.map(cleanPaths) expect(p[0]).toEqual('.redwood/types/includes/web-routesPages.d.ts') const c = fs.readFileSync(paths[0], 'utf-8') expect(c).toContain(` declare global { const BarPage: typeof BarPageType const FatalErrorPage: typeof FatalErrorPageType const FooPage: typeof FooPageType const HomePage: typeof HomePageType const NotFoundPage: typeof NotFoundPageType const PrivatePage: typeof PrivatePageType const TypeScriptPage: typeof TypeScriptPageType const adminEditUserPage: typeof adminEditUserPageType }`) }) test('generate current user ', () => { const paths = generateTypeDefCurrentUser() const p = paths.map(cleanPaths) expect(p[0]).toEqual('.redwood/types/includes/all-currentUser.d.ts') // The type definition output is static, so there's nothing to test. }) test('generates the router routes', () => { const paths = generateTypeDefRouterRoutes() const p = paths.map(cleanPaths) expect(p[0]).toEqual('.redwood/types/includes/web-routerRoutes.d.ts') const c = fs.readFileSync(paths[0], 'utf-8') expect(c).toContain(` home: (params?: RouteParams<"/"> & QueryParams) => "/" typescriptPage: (params?: RouteParams<"/typescript"> & QueryParams) => "/typescript" someOtherPage: (params?: RouteParams<"/somewhereElse"> & QueryParams) => "/somewhereElse" fooPage: (params?: RouteParams<"/foo"> & QueryParams) => "/foo" barPage: (params?: RouteParams<"/bar"> & QueryParams) => "/bar" privatePage: (params?: RouteParams<"/private-page"> & QueryParams) => "/private-page" `) }) test('generate glob imports', () => { const paths = generateTypeDefGlobImports() const p = paths.map(cleanPaths) expect(p[0]).toEqual('.redwood/types/includes/api-globImports.d.ts') }) test('generate api global context', () => { const paths = generateTypeDefGlobalContext() const p = paths.map(cleanPaths) expect(p[0]).toEqual('.redwood/types/includes/api-globalContext.d.ts') }) test('generate scenario type defs', () => { const paths = generateTypeDefScenarios() const p = paths.map(cleanPaths) expect(p[0]).toEqual('.redwood/types/includes/api-scenarios.d.ts') }) test('mirror path for directory named modules', () => { const d = findDirectoryNamedModules() const p = mirrorPathForDirectoryNamedModules(d[0]) expect(cleanPaths(p[0])).toMatchSnapshot() expect(cleanPaths(p[1])).toMatchSnapshot() }) test('mirror path for dir cells', () => { const c = findCells() const p = mirrorPathForCell(c[0]) expect(cleanPaths(p[0])).toMatchInlineSnapshot( `".redwood/types/mirror/web/src/components/NumTodosCell"` ) })
5,562
0
petrpan-code/redwoodjs/redwood/packages/internal/src
petrpan-code/redwoodjs/redwood/packages/internal/src/__tests__/validateSchema.test.ts
import path from 'path' import { loadAndValidateSdls } from '../validateSchema' const FIXTURE_PATH = path.resolve( __dirname, '../../../../__fixtures__/example-todo-main' ) beforeAll(() => { process.env.RWJS_CWD = FIXTURE_PATH }) afterAll(() => { delete process.env.RWJS_CWD }) test('Validates correctly on all platforms', async () => { await expect(loadAndValidateSdls()).resolves.not.toThrowError() })
5,563
0
petrpan-code/redwoodjs/redwood/packages/internal/src
petrpan-code/redwoodjs/redwood/packages/internal/src/__tests__/validateSchemaForAuthDirectives.test.ts
import path from 'path' import { CodeFileLoader } from '@graphql-tools/code-file-loader' import { loadTypedefs } from '@graphql-tools/load' import { mergeTypeDefs } from '@graphql-tools/merge' import type { DocumentNode } from 'graphql' import { getPaths } from '@redwoodjs/project-config' import { validateSchema, DIRECTIVE_REQUIRED_ERROR_MESSAGE, DIRECTIVE_INVALID_ROLE_TYPES_ERROR_MESSAGE, } from '../validateSchema' const FIXTURE_ERROR_PATH = path.resolve( __dirname, '../../../../__fixtures__/example-todo-main-with-errors' ) const projectTypeSrc = async (sdlFile: string) => await loadTypedefs([`graphql/**/${sdlFile}.sdl.{js,ts}`], { loaders: [ new CodeFileLoader({ noRequire: true, pluckConfig: { globalGqlIdentifierName: 'gql', }, }), ], cwd: getPaths().api.src, }) const validateSdlFile = async (sdlFile: string) => { const projectTypeSrcFiles = await projectTypeSrc(sdlFile) // The output of the above function doesn't give us the documents directly const projectDocumentNodes = Object.values(projectTypeSrcFiles) .map(({ document }) => document) .filter((documentNode): documentNode is DocumentNode => { return !!documentNode }) // Merge in the rootSchema with JSON scalars, etc. const mergedDocumentNode = mergeTypeDefs([projectDocumentNodes]) validateSchema(mergedDocumentNode) } describe('SDL uses auth directives', () => { beforeAll(() => { process.env.RWJS_CWD = FIXTURE_ERROR_PATH }) afterAll(() => { delete process.env.RWJS_CWD }) describe('SDL is valid', () => { test('with proper roles set on directives', async () => { await expect( validateSdlFile('todosWithAuthRoles') ).resolves.not.toThrowError() }) test('with uppercase single string roles declared on a Mutation', async () => { await expect( validateSdlFile('todosMutations') ).resolves.not.toThrowError() }) test('with a built-in @deprecated directive', async () => { await expect( validateSdlFile('todosWithBuiltInDirectives') ).resolves.not.toThrowError() }) }) describe('SDL is invalid', () => { test('because missing directives', async () => { await expect(validateSdlFile('todos')).rejects.toThrowError( DIRECTIVE_REQUIRED_ERROR_MESSAGE ) }) test('due to auth role errors', async () => { await expect( validateSdlFile('todosWithAuthInvalidRolesErrors') ).rejects.toThrowError(DIRECTIVE_INVALID_ROLE_TYPES_ERROR_MESSAGE) }) test('due to auth role errors when the role is missing/null', async () => { await expect( validateSdlFile('todosWithAuthMissingRoleError') ).rejects.toThrowError(DIRECTIVE_INVALID_ROLE_TYPES_ERROR_MESSAGE) }) test('due to auth role being numeric instead of string', async () => { await expect( validateSdlFile('todosWithAuthMissingRoleError') ).rejects.toThrowError(DIRECTIVE_INVALID_ROLE_TYPES_ERROR_MESSAGE) }) describe('and SDL missing the roles attribute', () => { test('due to requireAuthDirective missing roles attribute but argument value is a string', async () => { await expect( validateSdlFile('todosWithMissingAuthRolesAttributeError') ).rejects.toThrowError( 'Syntax Error: Expected Name, found String "ADMIN"' ) }) test('due to requireAuthDirective missing roles attribute when argument value is numeric', async () => { await expect( validateSdlFile('todosWithMissingAuthRolesAttributeNumericError') ).rejects.toThrowError('Syntax Error: Expected Name, found Int "42".') }) }) }) })
5,564
0
petrpan-code/redwoodjs/redwood/packages/internal/src
petrpan-code/redwoodjs/redwood/packages/internal/src/__tests__/validateSchemaForReservedNames.test.ts
import path from 'path' import type { DocumentNode } from 'graphql' import gql from 'graphql-tag' import { validateSchema } from '../validateSchema' const FIXTURE_PATH = path.resolve( __dirname, '../../../../__fixtures__/example-todo-main' ) beforeAll(() => { process.env.RWJS_CWD = FIXTURE_PATH }) afterAll(() => { delete process.env.RWJS_CWD }) const validateSdlFile = async (document: DocumentNode) => { validateSchema(document) } describe('SDL with no reserved names used', () => { describe('SDL is valid', () => { test('with proper type definition names', async () => { const document = gql` type Message { from: String body: String } type Query { room(id: ID!): [Message!]! @skipAuth } input SendMessageInput { roomId: ID! from: String! body: String! } type Mutation { sendMessage(input: SendMessageInput!): Message! @skipAuth } ` await expect(validateSdlFile(document)).resolves.not.toThrowError() }) test('with proper interface interface definition names', async () => { const document = gql` interface Node { id: ID! } type Message implements Node { id: ID! from: String body: String } type Query { room(id: ID!): [Message!]! @skipAuth } ` await expect(validateSdlFile(document)).resolves.not.toThrowError() }) test('with proper interface input type definition names', async () => { const document = gql` type Message { from: String body: String } type Query { room(id: ID!): [Message!]! @skipAuth } input SendMessageInput { roomId: ID! from: String! body: String! } type Mutation { sendMessage(input: SendMessageInput!): Message! @skipAuth } ` await expect(validateSdlFile(document)).resolves.not.toThrowError() }) }) describe('SDL is invalid', () => { test('because uses a reserved name as a type', async () => { const document = gql` type Float { from: String body: String } type Query { room(id: ID!): [Message!]! @skipAuth } input SendMessageInput { roomId: ID! from: String! body: String! } type Mutation { sendMessage(input: SendMessageInput!): Message! @skipAuth } ` await expect( validateSdlFile(document) ).rejects.toThrowErrorMatchingSnapshot() }) }) test('because uses a reserved name as an input', async () => { const document = gql` type Message { from: String body: String } type Query { room(id: ID!): [Message!]! @skipAuth } input Float { roomId: ID! from: String! body: String! } type Mutation { sendMessage(input: SendMessageInput!): Message! @skipAuth } ` await expect( validateSdlFile(document) ).rejects.toThrowErrorMatchingSnapshot() }) test('because uses a reserved name as an interface', async () => { const document = gql` interface Float { id: ID! } type Message implements Float { id: ID! from: String body: String } type Query { room(id: ID!): [Message!]! @skipAuth } input SendMessageInput { roomId: ID! from: String! body: String! } type Mutation { sendMessage(input: SendMessageInput!): Message! @skipAuth } ` await expect( validateSdlFile(document) ).rejects.toThrowErrorMatchingSnapshot() }) })
5,565
0
petrpan-code/redwoodjs/redwood/packages/internal/src
petrpan-code/redwoodjs/redwood/packages/internal/src/__tests__/validateSchemaWithErrors.test.ts
import path from 'path' import { DIRECTIVE_INVALID_ROLE_TYPES_ERROR_MESSAGE, DIRECTIVE_REQUIRED_ERROR_MESSAGE, loadAndValidateSdls, } from '../validateSchema' const FIXTURE_ERROR_PATH = path.resolve( __dirname, '../../../../__fixtures__/example-todo-main-with-errors' ) describe('SDL is missing directives', () => { beforeAll(() => { process.env.RWJS_CWD = FIXTURE_ERROR_PATH }) afterAll(() => { delete process.env.RWJS_CWD }) test('is invalid due to missing directives', async () => { await expect(loadAndValidateSdls()).rejects.toThrowError( DIRECTIVE_REQUIRED_ERROR_MESSAGE ) }) test('does not throw an error due to invalid roles', async () => { await expect(loadAndValidateSdls()).rejects.not.toThrowError( DIRECTIVE_INVALID_ROLE_TYPES_ERROR_MESSAGE ) }) })
5,566
0
petrpan-code/redwoodjs/redwood/packages/internal/src/__tests__
petrpan-code/redwoodjs/redwood/packages/internal/src/__tests__/__snapshots__/graphqlCodeGen.test.ts.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`Generate gql typedefs api 1`] = ` "import { Prisma } from "@prisma/client" import { MergePrismaWithSdlTypes, MakeRelationsOptional } from '@redwoodjs/api' import { PrismaModelOne as PrismaPrismaModelOne, PrismaModelTwo as PrismaPrismaModelTwo, Post as PrismaPost, Todo as PrismaTodo } from '@prisma/client' import { GraphQLResolveInfo, GraphQLScalarType, GraphQLScalarTypeConfig } from 'graphql'; import { RedwoodGraphQLContext } from '@redwoodjs/graphql-server/dist/types'; export type Maybe<T> = T | null; export type InputMaybe<T> = Maybe<T>; export type Exact<T extends { [key: string]: unknown }> = { [K in keyof T]: T[K] }; export type MakeOptional<T, K extends keyof T> = Omit<T, K> & { [SubKey in K]?: Maybe<T[SubKey]> }; export type MakeMaybe<T, K extends keyof T> = Omit<T, K> & { [SubKey in K]: Maybe<T[SubKey]> }; export type ResolverFn<TResult, TParent, TContext, TArgs> = ( args?: TArgs, obj?: { root: TParent; context: TContext; info: GraphQLResolveInfo } ) => TResult | Promise<TResult> export type RequireFields<T, K extends keyof T> = Omit<T, K> & { [P in K]-?: NonNullable<T[P]> }; export type OptArgsResolverFn<TResult, TParent = {}, TContext = {}, TArgs = {}> = ( args?: TArgs, obj?: { root: TParent; context: TContext; info: GraphQLResolveInfo } ) => TResult | Promise<TResult> export type RequiredResolverFn<TResult, TParent = {}, TContext = {}, TArgs = {}> = ( args: TArgs, obj: { root: TParent; context: TContext; info: GraphQLResolveInfo } ) => TResult | Promise<TResult> /** All built-in and custom scalars, mapped to their actual values */ export type Scalars = { ID: string; String: string; Boolean: boolean; Int: number; Float: number; BigInt: number; Date: Date | string; DateTime: Date | string; JSON: Prisma.JsonValue; JSONObject: Prisma.JsonObject; Time: Date | string; }; export type Mutation = { __typename?: 'Mutation'; createTodo?: Maybe<Todo>; renameTodo?: Maybe<Todo>; updateTodoStatus?: Maybe<Todo>; }; export type MutationcreateTodoArgs = { body: Scalars['String']; }; export type MutationrenameTodoArgs = { body: Scalars['String']; id: Scalars['Int']; }; export type MutationupdateTodoStatusArgs = { id: Scalars['Int']; status: Scalars['String']; }; /** About the Redwood queries. */ export type Query = { __typename?: 'Query'; currentUser?: Maybe<Scalars['JSON']>; /** Fetches the Redwood root schema. */ redwood?: Maybe<Redwood>; todos?: Maybe<Array<Maybe<Todo>>>; todosCount: Scalars['Int']; }; /** * The RedwoodJS Root Schema * * Defines details about RedwoodJS such as the current user and version information. */ export type Redwood = { __typename?: 'Redwood'; /** The current user. */ currentUser?: Maybe<Scalars['JSON']>; /** The version of Prisma. */ prismaVersion?: Maybe<Scalars['String']>; /** The version of Redwood. */ version?: Maybe<Scalars['String']>; }; export type Todo = { __typename?: 'Todo'; body: Scalars['String']; id: Scalars['Int']; status: Scalars['String']; }; type MaybeOrArrayOfMaybe<T> = T | Maybe<T> | Maybe<T>[]; type AllMappedModels = MaybeOrArrayOfMaybe<Todo> export type ResolverTypeWrapper<T> = Promise<T> | T; export type Resolver<TResult, TParent = {}, TContext = {}, TArgs = {}> = ResolverFn<TResult, TParent, TContext, TArgs>; export type SubscriptionSubscribeFn<TResult, TParent, TContext, TArgs> = ( parent: TParent, args: TArgs, context: TContext, info: GraphQLResolveInfo ) => AsyncIterable<TResult> | Promise<AsyncIterable<TResult>>; export type SubscriptionResolveFn<TResult, TParent, TContext, TArgs> = ( parent: TParent, args: TArgs, context: TContext, info: GraphQLResolveInfo ) => TResult | Promise<TResult>; export interface SubscriptionSubscriberObject<TResult, TKey extends string, TParent, TContext, TArgs> { subscribe: SubscriptionSubscribeFn<{ [key in TKey]: TResult }, TParent, TContext, TArgs>; resolve?: SubscriptionResolveFn<TResult, { [key in TKey]: TResult }, TContext, TArgs>; } export interface SubscriptionResolverObject<TResult, TParent, TContext, TArgs> { subscribe: SubscriptionSubscribeFn<any, TParent, TContext, TArgs>; resolve: SubscriptionResolveFn<TResult, any, TContext, TArgs>; } export type SubscriptionObject<TResult, TKey extends string, TParent, TContext, TArgs> = | SubscriptionSubscriberObject<TResult, TKey, TParent, TContext, TArgs> | SubscriptionResolverObject<TResult, TParent, TContext, TArgs>; export type SubscriptionResolver<TResult, TKey extends string, TParent = {}, TContext = {}, TArgs = {}> = | ((...args: any[]) => SubscriptionObject<TResult, TKey, TParent, TContext, TArgs>) | SubscriptionObject<TResult, TKey, TParent, TContext, TArgs>; export type TypeResolveFn<TTypes, TParent = {}, TContext = {}> = ( parent: TParent, context: TContext, info: GraphQLResolveInfo ) => Maybe<TTypes> | Promise<Maybe<TTypes>>; export type IsTypeOfResolverFn<T = {}, TContext = {}> = (obj: T, context: TContext, info: GraphQLResolveInfo) => boolean | Promise<boolean>; export type NextResolverFn<T> = () => Promise<T>; export type DirectiveResolverFn<TResult = {}, TParent = {}, TContext = {}, TArgs = {}> = ( next: NextResolverFn<TResult>, parent: TParent, args: TArgs, context: TContext, info: GraphQLResolveInfo ) => TResult | Promise<TResult>; /** Mapping between all available schema types and the resolvers types */ export type ResolversTypes = { BigInt: ResolverTypeWrapper<Scalars['BigInt']>; Boolean: ResolverTypeWrapper<Scalars['Boolean']>; Date: ResolverTypeWrapper<Scalars['Date']>; DateTime: ResolverTypeWrapper<Scalars['DateTime']>; Int: ResolverTypeWrapper<Scalars['Int']>; JSON: ResolverTypeWrapper<Scalars['JSON']>; JSONObject: ResolverTypeWrapper<Scalars['JSONObject']>; Mutation: ResolverTypeWrapper<{}>; Query: ResolverTypeWrapper<{}>; Redwood: ResolverTypeWrapper<Redwood>; String: ResolverTypeWrapper<Scalars['String']>; Time: ResolverTypeWrapper<Scalars['Time']>; Todo: ResolverTypeWrapper<MergePrismaWithSdlTypes<PrismaTodo, MakeRelationsOptional<Todo, AllMappedModels>, AllMappedModels>>; }; /** Mapping between all available schema types and the resolvers parents */ export type ResolversParentTypes = { BigInt: Scalars['BigInt']; Boolean: Scalars['Boolean']; Date: Scalars['Date']; DateTime: Scalars['DateTime']; Int: Scalars['Int']; JSON: Scalars['JSON']; JSONObject: Scalars['JSONObject']; Mutation: {}; Query: {}; Redwood: Redwood; String: Scalars['String']; Time: Scalars['Time']; Todo: MergePrismaWithSdlTypes<PrismaTodo, MakeRelationsOptional<Todo, AllMappedModels>, AllMappedModels>; }; export type requireAuthDirectiveArgs = { roles?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type requireAuthDirectiveResolver<Result, Parent, ContextType = RedwoodGraphQLContext, Args = requireAuthDirectiveArgs> = DirectiveResolverFn<Result, Parent, ContextType, Args>; export type skipAuthDirectiveArgs = { }; export type skipAuthDirectiveResolver<Result, Parent, ContextType = RedwoodGraphQLContext, Args = skipAuthDirectiveArgs> = DirectiveResolverFn<Result, Parent, ContextType, Args>; export interface BigIntScalarConfig extends GraphQLScalarTypeConfig<ResolversTypes['BigInt'], any> { name: 'BigInt'; } export interface DateScalarConfig extends GraphQLScalarTypeConfig<ResolversTypes['Date'], any> { name: 'Date'; } export interface DateTimeScalarConfig extends GraphQLScalarTypeConfig<ResolversTypes['DateTime'], any> { name: 'DateTime'; } export interface JSONScalarConfig extends GraphQLScalarTypeConfig<ResolversTypes['JSON'], any> { name: 'JSON'; } export interface JSONObjectScalarConfig extends GraphQLScalarTypeConfig<ResolversTypes['JSONObject'], any> { name: 'JSONObject'; } export type MutationResolvers<ContextType = RedwoodGraphQLContext, ParentType extends ResolversParentTypes['Mutation'] = ResolversParentTypes['Mutation']> = { createTodo: Resolver<Maybe<ResolversTypes['Todo']>, ParentType, ContextType, RequireFields<MutationcreateTodoArgs, 'body'>>; renameTodo: Resolver<Maybe<ResolversTypes['Todo']>, ParentType, ContextType, RequireFields<MutationrenameTodoArgs, 'body' | 'id'>>; updateTodoStatus: Resolver<Maybe<ResolversTypes['Todo']>, ParentType, ContextType, RequireFields<MutationupdateTodoStatusArgs, 'id' | 'status'>>; }; export type MutationRelationResolvers<ContextType = RedwoodGraphQLContext, ParentType extends ResolversParentTypes['Mutation'] = ResolversParentTypes['Mutation']> = { createTodo?: RequiredResolverFn<Maybe<ResolversTypes['Todo']>, ParentType, ContextType, RequireFields<MutationcreateTodoArgs, 'body'>>; renameTodo?: RequiredResolverFn<Maybe<ResolversTypes['Todo']>, ParentType, ContextType, RequireFields<MutationrenameTodoArgs, 'body' | 'id'>>; updateTodoStatus?: RequiredResolverFn<Maybe<ResolversTypes['Todo']>, ParentType, ContextType, RequireFields<MutationupdateTodoStatusArgs, 'id' | 'status'>>; }; export type QueryResolvers<ContextType = RedwoodGraphQLContext, ParentType extends ResolversParentTypes['Query'] = ResolversParentTypes['Query']> = { currentUser: OptArgsResolverFn<Maybe<ResolversTypes['JSON']>, ParentType, ContextType>; redwood: OptArgsResolverFn<Maybe<ResolversTypes['Redwood']>, ParentType, ContextType>; todos: OptArgsResolverFn<Maybe<Array<Maybe<ResolversTypes['Todo']>>>, ParentType, ContextType>; todosCount: OptArgsResolverFn<ResolversTypes['Int'], ParentType, ContextType>; }; export type QueryRelationResolvers<ContextType = RedwoodGraphQLContext, ParentType extends ResolversParentTypes['Query'] = ResolversParentTypes['Query']> = { currentUser?: RequiredResolverFn<Maybe<ResolversTypes['JSON']>, ParentType, ContextType>; redwood?: RequiredResolverFn<Maybe<ResolversTypes['Redwood']>, ParentType, ContextType>; todos?: RequiredResolverFn<Maybe<Array<Maybe<ResolversTypes['Todo']>>>, ParentType, ContextType>; todosCount?: RequiredResolverFn<ResolversTypes['Int'], ParentType, ContextType>; }; export type RedwoodResolvers<ContextType = RedwoodGraphQLContext, ParentType extends ResolversParentTypes['Redwood'] = ResolversParentTypes['Redwood']> = { currentUser: OptArgsResolverFn<Maybe<ResolversTypes['JSON']>, ParentType, ContextType>; prismaVersion: OptArgsResolverFn<Maybe<ResolversTypes['String']>, ParentType, ContextType>; version: OptArgsResolverFn<Maybe<ResolversTypes['String']>, ParentType, ContextType>; __isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>; }; export type RedwoodRelationResolvers<ContextType = RedwoodGraphQLContext, ParentType extends ResolversParentTypes['Redwood'] = ResolversParentTypes['Redwood']> = { currentUser?: RequiredResolverFn<Maybe<ResolversTypes['JSON']>, ParentType, ContextType>; prismaVersion?: RequiredResolverFn<Maybe<ResolversTypes['String']>, ParentType, ContextType>; version?: RequiredResolverFn<Maybe<ResolversTypes['String']>, ParentType, ContextType>; __isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>; }; export interface TimeScalarConfig extends GraphQLScalarTypeConfig<ResolversTypes['Time'], any> { name: 'Time'; } export type TodoResolvers<ContextType = RedwoodGraphQLContext, ParentType extends ResolversParentTypes['Todo'] = ResolversParentTypes['Todo']> = { body: OptArgsResolverFn<ResolversTypes['String'], ParentType, ContextType>; id: OptArgsResolverFn<ResolversTypes['Int'], ParentType, ContextType>; status: OptArgsResolverFn<ResolversTypes['String'], ParentType, ContextType>; __isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>; }; export type TodoRelationResolvers<ContextType = RedwoodGraphQLContext, ParentType extends ResolversParentTypes['Todo'] = ResolversParentTypes['Todo']> = { body?: RequiredResolverFn<ResolversTypes['String'], ParentType, ContextType>; id?: RequiredResolverFn<ResolversTypes['Int'], ParentType, ContextType>; status?: RequiredResolverFn<ResolversTypes['String'], ParentType, ContextType>; __isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>; }; export type Resolvers<ContextType = RedwoodGraphQLContext> = { BigInt: GraphQLScalarType; Date: GraphQLScalarType; DateTime: GraphQLScalarType; JSON: GraphQLScalarType; JSONObject: GraphQLScalarType; Mutation: MutationResolvers<ContextType>; Query: QueryResolvers<ContextType>; Redwood: RedwoodResolvers<ContextType>; Time: GraphQLScalarType; Todo: TodoResolvers<ContextType>; }; export type DirectiveResolvers<ContextType = RedwoodGraphQLContext> = { requireAuth: requireAuthDirectiveResolver<any, any, ContextType>; skipAuth: skipAuthDirectiveResolver<any, any, ContextType>; }; " `; exports[`Generate gql typedefs web 1`] = ` "import { Prisma } from "@prisma/client" export type Maybe<T> = T | null; export type InputMaybe<T> = Maybe<T>; export type Exact<T extends { [key: string]: unknown }> = { [K in keyof T]: T[K] }; export type MakeOptional<T, K extends keyof T> = Omit<T, K> & { [SubKey in K]?: Maybe<T[SubKey]> }; export type MakeMaybe<T, K extends keyof T> = Omit<T, K> & { [SubKey in K]: Maybe<T[SubKey]> }; /** All built-in and custom scalars, mapped to their actual values */ export type Scalars = { ID: string; String: string; Boolean: boolean; Int: number; Float: number; BigInt: number; Date: string; DateTime: string; JSON: Prisma.JsonValue; JSONObject: Prisma.JsonObject; Time: string; }; export type Mutation = { __typename?: 'Mutation'; createTodo?: Maybe<Todo>; renameTodo?: Maybe<Todo>; updateTodoStatus?: Maybe<Todo>; }; export type MutationcreateTodoArgs = { body: Scalars['String']; }; export type MutationrenameTodoArgs = { body: Scalars['String']; id: Scalars['Int']; }; export type MutationupdateTodoStatusArgs = { id: Scalars['Int']; status: Scalars['String']; }; /** About the Redwood queries. */ export type Query = { __typename?: 'Query'; currentUser?: Maybe<Scalars['JSON']>; /** Fetches the Redwood root schema. */ redwood?: Maybe<Redwood>; todos?: Maybe<Array<Maybe<Todo>>>; todosCount: Scalars['Int']; }; /** * The RedwoodJS Root Schema * * Defines details about RedwoodJS such as the current user and version information. */ export type Redwood = { __typename?: 'Redwood'; /** The current user. */ currentUser?: Maybe<Scalars['JSON']>; /** The version of Prisma. */ prismaVersion?: Maybe<Scalars['String']>; /** The version of Redwood. */ version?: Maybe<Scalars['String']>; }; export type Todo = { __typename?: 'Todo'; body: Scalars['String']; id: Scalars['Int']; status: Scalars['String']; }; export type AddTodo_CreateTodoVariables = Exact<{ body: Scalars['String']; }>; export type AddTodo_CreateTodo = { __typename?: 'Mutation', createTodo?: { __typename: 'Todo', id: number, body: string, status: string } | null }; export type NumTodosCell_GetCountVariables = Exact<{ [key: string]: never; }>; export type NumTodosCell_GetCount = { __typename?: 'Query', todosCount: number }; export type TodoListCell_GetTodosVariables = Exact<{ [key: string]: never; }>; export type TodoListCell_GetTodos = { __typename?: 'Query', todos?: Array<{ __typename?: 'Todo', id: number, body: string, status: string } | null> | null }; export type TodoListCell_CheckTodoVariables = Exact<{ id: Scalars['Int']; status: Scalars['String']; }>; export type TodoListCell_CheckTodo = { __typename?: 'Mutation', updateTodoStatus?: { __typename: 'Todo', id: number, status: string } | null }; " `;
5,567
0
petrpan-code/redwoodjs/redwood/packages/internal/src/__tests__
petrpan-code/redwoodjs/redwood/packages/internal/src/__tests__/__snapshots__/graphqlSchema.test.ts.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`Generates GraphQL schema 1`] = ` "directive @requireAuth(roles: [String]) on FIELD_DEFINITION directive @skipAuth on FIELD_DEFINITION scalar BigInt scalar Date scalar DateTime scalar JSON scalar JSONObject type Mutation { createTodo(body: String!): Todo renameTodo(body: String!, id: Int!): Todo updateTodoStatus(id: Int!, status: String!): Todo } """About the Redwood queries.""" type Query { currentUser: JSON """Fetches the Redwood root schema.""" redwood: Redwood todos: [Todo] todosCount: Int! } """ The RedwoodJS Root Schema Defines details about RedwoodJS such as the current user and version information. """ type Redwood { """The current user.""" currentUser: JSON """The version of Prisma.""" prismaVersion: String """The version of Redwood.""" version: String } scalar Time type Todo { body: String! id: Int! status: String! }" `; exports[`Includes live query directive if serverful and realtime 1`] = ` """" Instruction for establishing a live connection that is updated once the underlying data changes. """ directive @live( """Whether the query should be live or not.""" if: Boolean = true """ Propose a desired throttle interval ot the server in order to receive updates to at most once per "throttle" milliseconds. The server must not accept this value. """ throttle: Int ) on QUERY directive @requireAuth(roles: [String]) on FIELD_DEFINITION directive @skipAuth on FIELD_DEFINITION scalar BigInt scalar Date scalar DateTime scalar JSON scalar JSONObject type Mutation { createTodo(body: String!): Todo renameTodo(body: String!, id: Int!): Todo updateTodoStatus(id: Int!, status: String!): Todo } """About the Redwood queries.""" type Query { currentUser: JSON """Fetches the Redwood root schema.""" redwood: Redwood todos: [Todo] todosCount: Int! } """ The RedwoodJS Root Schema Defines details about RedwoodJS such as the current user and version information. """ type Redwood { """The current user.""" currentUser: JSON """The version of Prisma.""" prismaVersion: String """The version of Redwood.""" version: String } scalar Time type Todo { body: String! id: Int! status: String! }" `;
5,568
0
petrpan-code/redwoodjs/redwood/packages/internal/src/__tests__
petrpan-code/redwoodjs/redwood/packages/internal/src/__tests__/__snapshots__/possibleTypes.test.ts.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`Generate gql possible types web from the GraphQL Schema when toml has graphql possible types turned om when there are union types 1`] = ` "export interface PossibleTypesResultData { possibleTypes: { [key: string]: string[] } } const result: PossibleTypesResultData = { possibleTypes: { Groceries: ['Fruit', 'Vegetable'], Grocery: ['Fruit', 'Vegetable'], }, } export default result " `;
5,569
0
petrpan-code/redwoodjs/redwood/packages/internal/src/__tests__
petrpan-code/redwoodjs/redwood/packages/internal/src/__tests__/__snapshots__/typeDefinitions.test.ts.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`mirror path for directory named modules 1`] = `".redwood/types/mirror/web/src/graphql"`; exports[`mirror path for directory named modules 2`] = `"../../packages/internal/index.d.ts"`;
5,570
0
petrpan-code/redwoodjs/redwood/packages/internal/src/__tests__
petrpan-code/redwoodjs/redwood/packages/internal/src/__tests__/__snapshots__/validateSchemaForReservedNames.test.ts.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`SDL with no reserved names used SDL is invalid because uses a reserved name as a type 1`] = ` "The type named 'Float' is a reserved GraphQL name. Please rename it to something more specific, like: ApplicationFloat. " `; exports[`SDL with no reserved names used because uses a reserved name as an input 1`] = ` "The input type named 'Float' is a reserved GraphQL name. Please rename it to something more specific, like: ApplicationFloat. " `; exports[`SDL with no reserved names used because uses a reserved name as an interface 1`] = ` "The interface named 'Float' is a reserved GraphQL name. Please rename it to something more specific, like: ApplicationFloat. " `;
5,575
0
petrpan-code/redwoodjs/redwood/packages/internal/src/__tests__/fixtures/api
petrpan-code/redwoodjs/redwood/packages/internal/src/__tests__/fixtures/api/test/test.ts
export const hello = ""
5,671
0
petrpan-code/redwoodjs/redwood/packages/mailer/core/src
petrpan-code/redwoodjs/redwood/packages/mailer/core/src/__tests__/mailer.test.ts
import { AbstractMailHandler } from '../handler' import { Mailer } from '../mailer' import { AbstractMailRenderer } from '../renderer' import type { MailRenderedContent, MailSendOptionsComplete, MailUtilities, MailResult, MailRendererOptions, } from '../types' class MockMailHandler extends AbstractMailHandler { send( _renderedContent: MailRenderedContent, _sendOptions: MailSendOptionsComplete, _handlerOptions?: Record<string | number | symbol, unknown> | undefined, _utilities?: MailUtilities | undefined ): MailResult | Promise<MailResult> { // do nothing return {} } internal(): Record<string, unknown> { return {} } } class MockMailRenderer extends AbstractMailRenderer { render( _template: unknown, _options: MailRendererOptions<unknown>, _utilities?: MailUtilities | undefined ): MailRenderedContent { // do nothing return { html: '', text: '', } } internal(): Record<string, unknown> { return {} } } describe('Uses the correct modes', () => { const baseConfig = { handling: { handlers: { handlerA: new MockMailHandler(), handlerB: new MockMailHandler(), }, default: 'handlerA', }, rendering: { renderers: { rendererA: new MockMailRenderer(), rendererB: new MockMailRenderer(), }, default: 'rendererA', }, } as const beforeAll(() => { // prevent console output jest.spyOn(console, 'log').mockImplementation(() => {}) jest.spyOn(console, 'warn').mockImplementation(() => {}) jest.spyOn(console, 'debug').mockImplementation(() => {}) }) afterAll(() => { jest.restoreAllMocks() }) describe('starts in test mode', () => { test('default', () => { const existingValue = process.env.NODE_ENV process.env.NODE_ENV = 'test' expect(new Mailer(baseConfig).mode).toBe('test') process.env.NODE_ENV = 'test-override' expect(new Mailer(baseConfig).mode).not.toBe('test') process.env.NODE_ENV = existingValue }) test('explicit boolean', () => { expect( new Mailer({ ...baseConfig, test: { when: true, }, }).mode ).toBe('test') expect( new Mailer({ ...baseConfig, test: { when: false, }, }).mode ).not.toBe('test') }) test('explicit function', () => { expect( new Mailer({ ...baseConfig, test: { when: () => true, }, }).mode ).toBe('test') expect( new Mailer({ ...baseConfig, test: { when: () => false, }, }).mode ).not.toBe('test') }) test('fails for other condition types', () => { expect(() => { const _mailer = new Mailer({ ...baseConfig, test: { // @ts-expect-error - test invalid type when: 123, }, }) }).toThrowErrorMatchingInlineSnapshot( `"Invalid 'when' configuration for test mode"` ) expect(() => { const _mailer = new Mailer({ ...baseConfig, test: { // @ts-expect-error - test invalid type when: 'invalid', }, }) }).toThrowErrorMatchingInlineSnapshot( `"Invalid 'when' configuration for test mode"` ) }) }) describe('starts in development mode', () => { test('default', () => { const existingValue = process.env.NODE_ENV process.env.NODE_ENV = 'anything-but-production' expect(new Mailer(baseConfig).mode).toBe('development') process.env.NODE_ENV = 'production' expect(new Mailer(baseConfig).mode).not.toBe('development') process.env.NODE_ENV = existingValue }) test('explicit boolean', () => { expect( new Mailer({ ...baseConfig, development: { when: true, }, test: { when: false, }, }).mode ).toBe('development') expect( new Mailer({ ...baseConfig, development: { when: false, }, test: { when: false, }, }).mode ).not.toBe('development') }) test('explicit function', () => { expect( new Mailer({ ...baseConfig, development: { when: () => true, }, test: { when: false, }, }).mode ).toBe('development') expect( new Mailer({ ...baseConfig, development: { when: () => false, }, test: { when: false, }, }).mode ).not.toBe('development') }) test('fails for other condition types', () => { expect(() => { const _mailer = new Mailer({ ...baseConfig, development: { // @ts-expect-error - test invalid type when: 123, }, test: { when: false, }, }) }).toThrowErrorMatchingInlineSnapshot( `"Invalid 'when' configuration for development mode"` ) expect(() => { const _mailer = new Mailer({ ...baseConfig, development: { // @ts-expect-error - test invalid type when: 'invalid', }, test: { when: false, }, }) }).toThrowErrorMatchingInlineSnapshot( `"Invalid 'when' configuration for development mode"` ) }) }) describe('starts in production mode', () => { test('default', () => { const existingValue = process.env.NODE_ENV process.env.NODE_ENV = 'production' expect(new Mailer(baseConfig).mode).toBe('production') process.env.NODE_ENV = 'anything-but-production' expect(new Mailer(baseConfig).mode).not.toBe('production') process.env.NODE_ENV = existingValue }) test('explicit boolean', () => { expect( new Mailer({ ...baseConfig, development: { when: false, }, test: { when: false, }, }).mode ).toBe('production') expect( new Mailer({ ...baseConfig, development: { when: true, }, test: { when: false, }, }).mode ).not.toBe('production') }) test('explicit function', () => { expect( new Mailer({ ...baseConfig, development: { when: () => false, }, test: { when: false, }, }).mode ).toBe('production') expect( new Mailer({ ...baseConfig, development: { when: () => true, }, test: { when: false, }, }).mode ).not.toBe('production') }) }) describe('warns about null handlers', () => { beforeAll(() => { jest.spyOn(console, 'warn').mockImplementation(() => {}) }) test('test', () => { console.warn.mockClear() const _mailer1 = new Mailer({ ...baseConfig, test: { when: true, handler: null, }, }) expect(console.warn).toBeCalledWith( 'The test handler is null, this will prevent mail from being processed in test mode' ) }) test('development', () => { console.warn.mockClear() const _mailer1 = new Mailer({ ...baseConfig, development: { when: true, handler: null, }, }) expect(console.warn).toBeCalledWith( 'The development handler is null, this will prevent mail from being processed in development mode' ) }) }) describe('attempts to use fallback handlers', () => { beforeAll(() => { jest.spyOn(console, 'warn').mockImplementation(() => {}) }) test('test', () => { console.warn.mockClear() const _mailer = new Mailer({ ...baseConfig, test: { when: true, handler: undefined, }, }) expect(console.warn).toBeCalledWith( "Automatically loaded the '@redwoodjs/mailer-handler-in-memory' handler, this will be used to process mail in test mode" ) }) test('development', () => { console.warn.mockClear() const _mailer = new Mailer({ ...baseConfig, development: { when: true, handler: undefined, }, }) expect(console.warn).toBeCalledWith( "Automatically loaded the '@redwoodjs/mailer-handler-studio' handler, this will be used to process mail in development mode" ) }) }) describe('detects missing default handler', () => { test('test', () => { expect(() => { const _mailer = new Mailer({ ...baseConfig, test: { when: true, // @ts-expect-error - test invalid type handler: 'handlerC', }, }) }).toThrowErrorMatchingInlineSnapshot( `"The specified test handler 'handlerC' is not defined"` ) }) test('development', () => { expect(() => { const _mailer = new Mailer({ ...baseConfig, development: { when: true, // @ts-expect-error - test invalid type handler: 'handlerC', }, }) }).toThrowErrorMatchingInlineSnapshot( `"The specified development handler 'handlerC' is not defined"` ) }) test('production', () => { expect(() => { const _mailer = new Mailer({ ...baseConfig, test: { when: false, }, development: { when: false, }, handling: { ...baseConfig.handling, // @ts-expect-error - test invalid type default: 'handlerC', }, }) }).toThrowErrorMatchingInlineSnapshot( `"The specified default handler 'handlerC' is not defined"` ) }) }) describe('detects missing default renderer', () => { test('test', () => { expect(() => { const _mailer = new Mailer({ ...baseConfig, test: { when: true, }, rendering: { ...baseConfig.rendering, // @ts-expect-error - test invalid type default: 'rendererC', }, }) }).toThrowErrorMatchingInlineSnapshot( `"The specified default renderer 'rendererC' is not defined"` ) }) test('development', () => { expect(() => { const _mailer = new Mailer({ ...baseConfig, development: { when: true, }, rendering: { ...baseConfig.rendering, // @ts-expect-error - test invalid type default: 'rendererC', }, }) }).toThrowErrorMatchingInlineSnapshot( `"The specified default renderer 'rendererC' is not defined"` ) }) test('production', () => { expect(() => { const _mailer = new Mailer({ ...baseConfig, test: { when: false, }, development: { when: false, }, rendering: { ...baseConfig.rendering, // @ts-expect-error - test invalid type default: 'rendererC', }, }) }).toThrowErrorMatchingInlineSnapshot( `"The specified default renderer 'rendererC' is not defined"` ) }) }) describe('calls the correct handler and renderer function', () => { jest.spyOn(console, 'debug').mockImplementation(() => {}) describe('test', () => { const testHandler = new MockMailHandler() const testRenderer = new MockMailRenderer() const mailerConfig = { ...baseConfig, handling: { ...baseConfig.handling, handlers: { ...baseConfig.handling.handlers, testHandler, }, }, rendering: { ...baseConfig.rendering, renderers: { ...baseConfig.rendering.renderers, testRenderer, }, default: 'testRenderer', }, test: { when: true, handler: 'testHandler', }, development: { when: false, handler: 'handlerA', }, } as const const mailer = new Mailer(mailerConfig) beforeEach(() => { const handlerKeys = Object.keys(mailer.handlers) for (let i = 0; i < handlerKeys.length; i++) { const key = handlerKeys[i] jest.spyOn(mailer.handlers[key], 'send') } const rendererKeys = Object.keys(mailer.renderers) for (let i = 0; i < rendererKeys.length; i++) { const key = rendererKeys[i] jest.spyOn(mailer.renderers[key], 'render') } }) afterEach(() => { const handlerKeys = Object.keys(mailer.handlers) for (let i = 0; i < handlerKeys.length; i++) { const key = handlerKeys[i] if (mailer.handlers[key] === testHandler) { expect(mailer.handlers[key].send).toBeCalledTimes(1) } else { expect(mailer.handlers[key].send).toBeCalledTimes(0) } mailer.handlers[key].send.mockClear() } const rendererKeys = Object.keys(mailer.renderers) for (let i = 0; i < rendererKeys.length; i++) { const key = rendererKeys[i] mailer.renderers[key].render.mockClear() } }) test('send', async () => { await mailer.send(undefined, { to: '[email protected]', subject: 'Test', from: '[email protected]', }) const rendererKeys = Object.keys(mailer.renderers) for (let i = 0; i < rendererKeys.length; i++) { const key = rendererKeys[i] if (mailer.renderers[key] === testRenderer) { expect(mailer.renderers[key].render).toBeCalledTimes(1) } else { expect(mailer.renderers[key].render).toBeCalledTimes(0) } } }) test('sendWithoutRendering', async () => { await mailer.sendWithoutRendering( { text: 'text', html: '<html></html>', }, { to: '[email protected]', subject: 'Test', from: '[email protected]', } ) const rendererKeys = Object.keys(mailer.renderers) for (let i = 0; i < rendererKeys.length; i++) { const key = rendererKeys[i] expect(mailer.renderers[key].render).toBeCalledTimes(0) } }) }) describe('development', () => { const developmentHandler = new MockMailHandler() const developmentRenderer = new MockMailRenderer() const mailerConfig = { ...baseConfig, handling: { ...baseConfig.handling, handlers: { ...baseConfig.handling.handlers, developmentHandler, }, }, rendering: { ...baseConfig.rendering, renderers: { ...baseConfig.rendering.renderers, developmentRenderer, }, default: 'developmentRenderer', }, test: { when: false, handler: 'handlerA', }, development: { when: true, handler: 'developmentHandler', }, } as const const mailer = new Mailer(mailerConfig) beforeEach(() => { const handlerKeys = Object.keys(mailer.handlers) for (let i = 0; i < handlerKeys.length; i++) { const key = handlerKeys[i] jest.spyOn(mailer.handlers[key], 'send') } const rendererKeys = Object.keys(mailer.renderers) for (let i = 0; i < rendererKeys.length; i++) { const key = rendererKeys[i] jest.spyOn(mailer.renderers[key], 'render') } }) afterEach(() => { const handlerKeys = Object.keys(mailer.handlers) for (let i = 0; i < handlerKeys.length; i++) { const key = handlerKeys[i] if (mailer.handlers[key] === developmentHandler) { expect(mailer.handlers[key].send).toBeCalledTimes(1) } else { expect(mailer.handlers[key].send).toBeCalledTimes(0) } mailer.handlers[key].send.mockClear() } const rendererKeys = Object.keys(mailer.renderers) for (let i = 0; i < rendererKeys.length; i++) { const key = rendererKeys[i] mailer.renderers[key].render.mockClear() } }) test('send', async () => { await mailer.send(undefined, { to: '[email protected]', subject: 'Test', from: '[email protected]', }) const rendererKeys = Object.keys(mailer.renderers) for (let i = 0; i < rendererKeys.length; i++) { const key = rendererKeys[i] if (mailer.renderers[key] === developmentRenderer) { expect(mailer.renderers[key].render).toBeCalledTimes(1) } else { expect(mailer.renderers[key].render).toBeCalledTimes(0) } } }) test('sendWithoutRendering', async () => { await mailer.sendWithoutRendering( { text: 'text', html: '<html></html>', }, { to: '[email protected]', subject: 'Test', from: '[email protected]', } ) const rendererKeys = Object.keys(mailer.renderers) for (let i = 0; i < rendererKeys.length; i++) { const key = rendererKeys[i] expect(mailer.renderers[key].render).toBeCalledTimes(0) } }) }) describe('production', () => { const productionHandler = new MockMailHandler() const productionRenderer = new MockMailRenderer() const mailerConfig = { ...baseConfig, handling: { ...baseConfig.handling, handlers: { ...baseConfig.handling.handlers, productionHandler, }, default: 'productionHandler', }, rendering: { ...baseConfig.rendering, renderers: { ...baseConfig.rendering.renderers, productionRenderer, }, default: 'productionRenderer', }, test: { when: false, handler: 'handlerA', }, development: { when: false, handler: 'handlerA', }, } as const const mailer = new Mailer(mailerConfig) beforeEach(() => { const handlerKeys = Object.keys(mailer.handlers) for (let i = 0; i < handlerKeys.length; i++) { const key = handlerKeys[i] jest.spyOn(mailer.handlers[key], 'send') } const rendererKeys = Object.keys(mailer.renderers) for (let i = 0; i < rendererKeys.length; i++) { const key = rendererKeys[i] jest.spyOn(mailer.renderers[key], 'render') } }) afterEach(() => { const handlerKeys = Object.keys(mailer.handlers) for (let i = 0; i < handlerKeys.length; i++) { const key = handlerKeys[i] if (mailer.handlers[key] === productionHandler) { expect(mailer.handlers[key].send).toBeCalledTimes(1) } else { expect(mailer.handlers[key].send).toBeCalledTimes(0) } mailer.handlers[key].send.mockClear() } const rendererKeys = Object.keys(mailer.renderers) for (let i = 0; i < rendererKeys.length; i++) { const key = rendererKeys[i] mailer.renderers[key].render.mockClear() } }) test('send', async () => { await mailer.send(undefined, { to: '[email protected]', subject: 'Test', from: '[email protected]', }) const rendererKeys = Object.keys(mailer.renderers) for (let i = 0; i < rendererKeys.length; i++) { const key = rendererKeys[i] if (mailer.renderers[key] === productionRenderer) { expect(mailer.renderers[key].render).toBeCalledTimes(1) } else { expect(mailer.renderers[key].render).toBeCalledTimes(0) } } }) test('sendWithoutRendering', async () => { await mailer.sendWithoutRendering( { text: 'text', html: '<html></html>', }, { to: '[email protected]', subject: 'Test', from: '[email protected]', } ) const rendererKeys = Object.keys(mailer.renderers) for (let i = 0; i < rendererKeys.length; i++) { const key = rendererKeys[i] expect(mailer.renderers[key].render).toBeCalledTimes(0) } }) }) }) test('getTestHandler', () => { const handlerC = new MockMailHandler() const mailer = new Mailer({ ...baseConfig, handling: { ...baseConfig.handling, handlers: { ...baseConfig.handling.handlers, handlerC, }, }, test: { handler: 'handlerC', }, }) expect(mailer.getTestHandler()).toBe(handlerC) const mailerExplicitlyNullTestHandler = new Mailer({ ...baseConfig, test: { handler: null, }, }) expect(mailerExplicitlyNullTestHandler.getTestHandler()).toBeNull() const mailerNoTestHandlerDefined = new Mailer(baseConfig) expect(mailerNoTestHandlerDefined.getTestHandler()).not.toBeNull() }) test('getDevelopmentHandler', () => { const handlerC = new MockMailHandler() const mailer = new Mailer({ ...baseConfig, handling: { ...baseConfig.handling, handlers: { ...baseConfig.handling.handlers, handlerC, }, }, development: { handler: 'handlerC', }, }) expect(mailer.getDevelopmentHandler()).toBe(handlerC) const mailerExplicitlyNullDevelopmentHandler = new Mailer({ ...baseConfig, development: { handler: null, }, }) expect( mailerExplicitlyNullDevelopmentHandler.getDevelopmentHandler() ).toBeNull() const mailerNoDevelopmentHandlerDefined = new Mailer(baseConfig) expect( mailerNoDevelopmentHandlerDefined.getDevelopmentHandler() ).not.toBeNull() }) test('getDefaultProductionHandler', () => { const handlerC = new MockMailHandler() const mailer = new Mailer({ ...baseConfig, handling: { ...baseConfig.handling, handlers: { ...baseConfig.handling.handlers, handlerC, }, default: 'handlerC', }, }) expect(mailer.getDefaultProductionHandler()).toBe(handlerC) }) test('getDefaultHandler', () => { const handlerTest = new MockMailHandler() const handlerDev = new MockMailHandler() const handlerProd = new MockMailHandler() const mailerConfig = { ...baseConfig, handling: { ...baseConfig.handling, handlers: { ...baseConfig.handling.handlers, handlerTest, handlerDev, handlerProd, }, default: 'handlerProd', }, test: { handler: 'handlerTest', }, development: { handler: 'handlerDev', }, } as const const mailerTest = new Mailer({ ...mailerConfig, test: { ...mailerConfig.test, when: true }, development: { ...mailerConfig.development, when: false }, }) expect(mailerTest.getDefaultHandler()).toBe(handlerTest) const mailerDev = new Mailer({ ...mailerConfig, test: { ...mailerConfig.test, when: false }, development: { ...mailerConfig.development, when: true }, }) expect(mailerDev.getDefaultHandler()).toBe(handlerDev) const mailerProd = new Mailer({ ...mailerConfig, test: { ...mailerConfig.test, when: false }, development: { ...mailerConfig.development, when: false }, }) expect(mailerProd.getDefaultHandler()).toBe(handlerProd) }) test('getDefaultRenderer', () => { const rendererC = new MockMailRenderer() const mailer = new Mailer({ ...baseConfig, rendering: { ...baseConfig.rendering, renderers: { ...baseConfig.rendering.renderers, rendererC, }, default: 'rendererC', }, }) expect(mailer.getDefaultRenderer()).toBe(rendererC) }) })
5,672
0
petrpan-code/redwoodjs/redwood/packages/mailer/core/src
petrpan-code/redwoodjs/redwood/packages/mailer/core/src/__tests__/utils.test.ts
import type { MailerDefaults } from '../types' import { constructCompleteSendOptions, convertAddresses, extractDefaults, } from '../utils' describe('convertAddresses', () => { test('string passthrough', () => { const addresses = ['[email protected]', '[email protected]'] expect(convertAddresses(addresses)).toStrictEqual(addresses) }) test('object without name', () => { const addresses = [ { address: '[email protected]' }, { address: '[email protected]' }, ] expect(convertAddresses(addresses)).toStrictEqual([ '[email protected]', '[email protected]', ]) }) test('object with name', () => { const addresses = [ { address: '[email protected]', name: 'Alice McExampleton' }, { address: '[email protected]', name: 'Bob Testinger' }, ] expect(convertAddresses(addresses)).toStrictEqual([ 'Alice McExampleton <[email protected]>', 'Bob Testinger <[email protected]>', ]) }) }) describe('extractDefaults', () => { test('blank', () => { expect(extractDefaults({})).toStrictEqual({ attachments: [], bcc: [], cc: [], from: undefined, headers: {}, replyTo: undefined, }) }) test('example', () => { expect( extractDefaults({ from: '[email protected]', replyTo: '[email protected]', cc: ['[email protected]', '[email protected]'], bcc: { name: 'BCC Recipient', address: '[email protected]', }, headers: { 'X-Test-Header': 'test', }, attachments: [ { filename: 'test.txt', content: 'test', }, ], }) ).toStrictEqual({ attachments: [ { filename: 'test.txt', content: 'test', }, ], bcc: ['BCC Recipient <[email protected]>'], cc: ['[email protected]', '[email protected]'], from: '[email protected]', headers: { 'X-Test-Header': 'test', }, replyTo: '[email protected]', }) }) }) describe('constructCompleteSendOptions', () => { const blankDefaults: MailerDefaults = { attachments: [], bcc: [], cc: [], headers: {}, } test('minimal', () => { expect( constructCompleteSendOptions( { subject: 'Test Subject', to: '[email protected]', from: '[email protected]', }, blankDefaults ) ).toStrictEqual({ attachments: [], bcc: [], cc: [], from: '[email protected]', headers: {}, replyTo: undefined, subject: 'Test Subject', to: ['[email protected]'], }) }) test('throws when no from address is provided', () => { expect(() => { constructCompleteSendOptions( { subject: 'Test Subject', to: '[email protected]', }, blankDefaults ) }).toThrowErrorMatchingInlineSnapshot(`"Missing from address"`) expect(() => { constructCompleteSendOptions( { subject: 'Test Subject', to: '[email protected]', from: '[email protected]', }, blankDefaults ) }).not.toThrow() expect(() => { constructCompleteSendOptions( { subject: 'Test Subject', to: '[email protected]', }, { ...blankDefaults, from: '[email protected]' } ) }).not.toThrow() }) test('throws when no to address is provided', () => { expect(() => { constructCompleteSendOptions( // @ts-expect-error - intentionally missing 'to' { subject: 'Test Subject', from: '[email protected]', }, blankDefaults ) }).toThrowErrorMatchingInlineSnapshot(`"Missing to address"`) expect(() => { constructCompleteSendOptions( { subject: 'Test Subject', to: '[email protected]', from: '[email protected]', }, blankDefaults ) }).not.toThrow() }) test('throws when no subject is provided', () => { expect(() => { constructCompleteSendOptions( // @ts-expect-error - intentionally missing 'subject' { to: '[email protected]', from: '[email protected]', }, blankDefaults ) }).toThrowErrorMatchingInlineSnapshot(`"Missing subject"`) expect(() => { constructCompleteSendOptions( { subject: 'Test Subject', to: '[email protected]', from: '[email protected]', }, blankDefaults ) }).not.toThrow() }) test('converts addresses as appropriate', () => { expect( constructCompleteSendOptions( { subject: 'Test Subject', to: [ { name: 'name1', address: '[email protected]' }, { name: 'name2', address: '[email protected]' }, ], from: { name: 'fromName', address: '[email protected]' }, replyTo: { name: 'replyToName', address: '[email protected]', }, cc: [ { name: 'ccName1', address: '[email protected]' }, { name: 'ccName2', address: '[email protected]' }, ], bcc: [ { name: 'bccName1', address: '[email protected]' }, { name: 'bccName2', address: '[email protected]' }, ], }, blankDefaults ) ).toStrictEqual({ attachments: [], bcc: [ 'bccName1 <[email protected]>', 'bccName2 <[email protected]>', ], cc: [ 'ccName1 <[email protected]>', 'ccName2 <[email protected]>', ], from: 'fromName <[email protected]>', headers: {}, replyTo: 'replyToName <[email protected]>', subject: 'Test Subject', to: ['name1 <[email protected]>', 'name2 <[email protected]>'], }) }) test("handles 'from'", () => { expect( constructCompleteSendOptions( { subject: 'Test Subject', to: '[email protected]', from: '[email protected]', }, blankDefaults ) ).toStrictEqual({ attachments: [], bcc: [], cc: [], from: '[email protected]', headers: {}, replyTo: undefined, subject: 'Test Subject', to: ['[email protected]'], }) expect( constructCompleteSendOptions( { subject: 'Test Subject', to: '[email protected]', }, { ...blankDefaults, from: '[email protected]', } ) ).toStrictEqual({ attachments: [], bcc: [], cc: [], from: '[email protected]', headers: {}, replyTo: undefined, subject: 'Test Subject', to: ['[email protected]'], }) expect( constructCompleteSendOptions( { subject: 'Test Subject', to: '[email protected]', from: '[email protected]', }, { ...blankDefaults, from: '[email protected]', } ) ).toStrictEqual({ attachments: [], bcc: [], cc: [], from: '[email protected]', headers: {}, replyTo: undefined, subject: 'Test Subject', to: ['[email protected]'], }) }) test("handles 'subject'", () => { expect( constructCompleteSendOptions( { subject: 'Test Subject', to: '[email protected]', from: '[email protected]', }, blankDefaults ) ).toStrictEqual({ attachments: [], bcc: [], cc: [], from: '[email protected]', headers: {}, replyTo: undefined, subject: 'Test Subject', to: ['[email protected]'], }) }) test("handles 'cc'", () => { expect( constructCompleteSendOptions( { subject: 'Test Subject', to: '[email protected]', from: '[email protected]', cc: '[email protected]', }, blankDefaults ) ).toStrictEqual({ attachments: [], bcc: [], cc: ['[email protected]'], from: '[email protected]', headers: {}, replyTo: undefined, subject: 'Test Subject', to: ['[email protected]'], }) expect( constructCompleteSendOptions( { subject: 'Test Subject', to: '[email protected]', from: '[email protected]', }, { ...blankDefaults, cc: ['[email protected]'], } ) ).toStrictEqual({ attachments: [], bcc: [], cc: ['[email protected]'], from: '[email protected]', headers: {}, replyTo: undefined, subject: 'Test Subject', to: ['[email protected]'], }) expect( constructCompleteSendOptions( { subject: 'Test Subject', to: '[email protected]', from: '[email protected]', cc: ['[email protected]'], }, { ...blankDefaults, cc: ['[email protected]'], } ) ).toStrictEqual({ attachments: [], bcc: [], cc: ['[email protected]'], from: '[email protected]', headers: {}, replyTo: undefined, subject: 'Test Subject', to: ['[email protected]'], }) }) test("handles 'bcc'", () => { expect( constructCompleteSendOptions( { subject: 'Test Subject', to: '[email protected]', from: '[email protected]', bcc: '[email protected]', }, blankDefaults ) ).toStrictEqual({ attachments: [], bcc: ['[email protected]'], cc: [], from: '[email protected]', headers: {}, replyTo: undefined, subject: 'Test Subject', to: ['[email protected]'], }) expect( constructCompleteSendOptions( { subject: 'Test Subject', to: '[email protected]', from: '[email protected]', }, { ...blankDefaults, bcc: ['[email protected]'], } ) ).toStrictEqual({ attachments: [], bcc: ['[email protected]'], cc: [], from: '[email protected]', headers: {}, replyTo: undefined, subject: 'Test Subject', to: ['[email protected]'], }) expect( constructCompleteSendOptions( { subject: 'Test Subject', to: '[email protected]', from: '[email protected]', bcc: ['[email protected]'], }, { ...blankDefaults, bcc: ['[email protected]'], } ) ).toStrictEqual({ attachments: [], bcc: ['[email protected]'], cc: [], from: '[email protected]', headers: {}, replyTo: undefined, subject: 'Test Subject', to: ['[email protected]'], }) }) test("handles 'replyTo'", () => { expect( constructCompleteSendOptions( { subject: 'Test Subject', to: '[email protected]', from: '[email protected]', replyTo: '[email protected]', }, blankDefaults ) ).toStrictEqual({ attachments: [], bcc: [], cc: [], from: '[email protected]', headers: {}, replyTo: '[email protected]', subject: 'Test Subject', to: ['[email protected]'], }) expect( constructCompleteSendOptions( { subject: 'Test Subject', to: '[email protected]', from: '[email protected]', }, { ...blankDefaults, replyTo: '[email protected]', } ) ).toStrictEqual({ attachments: [], bcc: [], cc: [], from: '[email protected]', headers: {}, replyTo: '[email protected]', subject: 'Test Subject', to: ['[email protected]'], }) expect( constructCompleteSendOptions( { subject: 'Test Subject', to: '[email protected]', from: '[email protected]', replyTo: '[email protected]', }, { ...blankDefaults, replyTo: '[email protected]', } ) ).toStrictEqual({ attachments: [], bcc: [], cc: [], from: '[email protected]', headers: {}, replyTo: '[email protected]', subject: 'Test Subject', to: ['[email protected]'], }) }) test("handles 'headers'", () => { expect( constructCompleteSendOptions( { subject: 'Test Subject', to: '[email protected]', from: '[email protected]', headers: { 'X-Test-Header': 'test', }, }, blankDefaults ) ).toStrictEqual({ attachments: [], bcc: [], cc: [], from: '[email protected]', headers: { 'X-Test-Header': 'test', }, replyTo: undefined, subject: 'Test Subject', to: ['[email protected]'], }) expect( constructCompleteSendOptions( { subject: 'Test Subject', to: '[email protected]', from: '[email protected]', }, { ...blankDefaults, headers: { 'X-Test-Header': 'test', }, } ) ).toStrictEqual({ attachments: [], bcc: [], cc: [], from: '[email protected]', headers: { 'X-Test-Header': 'test', }, replyTo: undefined, subject: 'Test Subject', to: ['[email protected]'], }) expect( constructCompleteSendOptions( { subject: 'Test Subject', to: '[email protected]', from: '[email protected]', headers: { 'X-Test-Header-Override': 'test', }, }, { ...blankDefaults, headers: { 'X-Test-Header': 'test', }, } ) ).toStrictEqual({ attachments: [], bcc: [], cc: [], from: '[email protected]', headers: { 'X-Test-Header-Override': 'test', }, replyTo: undefined, subject: 'Test Subject', to: ['[email protected]'], }) }) test("handles 'attachments'", () => { expect( constructCompleteSendOptions( { subject: 'Test Subject', to: '[email protected]', from: '[email protected]', attachments: [ { filename: 'test.txt', content: 'test', }, ], }, blankDefaults ) ).toStrictEqual({ attachments: [ { filename: 'test.txt', content: 'test', }, ], bcc: [], cc: [], from: '[email protected]', headers: {}, replyTo: undefined, subject: 'Test Subject', to: ['[email protected]'], }) expect( constructCompleteSendOptions( { subject: 'Test Subject', to: '[email protected]', from: '[email protected]', }, { ...blankDefaults, attachments: [ { filename: 'test.txt', content: 'test', }, ], } ) ).toStrictEqual({ attachments: [ { filename: 'test.txt', content: 'test', }, ], bcc: [], cc: [], from: '[email protected]', headers: {}, replyTo: undefined, subject: 'Test Subject', to: ['[email protected]'], }) expect( constructCompleteSendOptions( { subject: 'Test Subject', to: '[email protected]', from: '[email protected]', attachments: [ { filename: 'testOverride.txt', content: 'testOverride', }, ], }, { ...blankDefaults, attachments: [ { filename: 'test.txt', content: 'test', }, ], } ) ).toStrictEqual({ attachments: [ { filename: 'testOverride.txt', content: 'testOverride', }, ], bcc: [], cc: [], from: '[email protected]', headers: {}, replyTo: undefined, subject: 'Test Subject', to: ['[email protected]'], }) }) })
5,718
0
petrpan-code/redwoodjs/redwood/packages/prerender/src
petrpan-code/redwoodjs/redwood/packages/prerender/src/__tests__/detectRoutes.test.ts
import type { RWRoute } from '@redwoodjs/structure/dist/model/RWRoute' import { detectPrerenderRoutes } from '../detection' jest.mock('@redwoodjs/project-config', () => { return { getPaths: jest.fn(() => { return { base: '/mock/path', web: `/mock/path/web`, } }), processPagesDir: jest.fn(() => []), } }) // Mock route detection, tested in @redwoodjs/structure separately let mockedRoutes: Partial<RWRoute>[] = [] jest.mock('@redwoodjs/structure', () => { return { getProject: jest.fn(() => { return { getRouter: jest.fn(() => { return { routes: mockedRoutes, } }), } }), } }) const expectPresence = (output, expectedOutput) => { expect(output).toContainEqual(expect.objectContaining(expectedOutput)) } describe('Detecting routes', () => { it('Should correctly detect routes with prerender prop', () => { mockedRoutes = [ { name: 'home', path: '/', prerender: true }, { name: 'private', path: '/private', prerender: false }, { name: 'about', path: '/about', prerender: true }, ] const output = detectPrerenderRoutes() expect(output.length).toBe(2) expectPresence(output, { name: 'home', path: '/' }) expectPresence(output, { name: 'about', path: '/about' }) expect(output).not.toContainEqual( expect.objectContaining({ name: 'private', path: '/private' }) ) }) it('Should render notFoundPage as 404.html', () => { mockedRoutes = [ { name: undefined, path: undefined, prerender: true, isNotFound: true, }, ] const output = detectPrerenderRoutes() expect(output.length).toBe(1) expect(output[0].name).toBe('404') expect(output[0].path).toBe('/404') }) it('Should also allow routes with params', () => { mockedRoutes = [ { name: 'taskDetail', path: '/task/${id}', hasParameters: true, prerender: true, }, ] const output = detectPrerenderRoutes() expect(output.length).toBe(1) }) it('Should return required keys', () => { mockedRoutes = [ { name: 'tasks', path: '/tasks', hasParameters: false, prerender: true, page: { filePath: '/mocked_path/tasks', }, }, { name: 'kittens', path: '/kittens', hasParameters: false, prerender: true, page: { filePath: '/mocked_path/Kittens.tsx', }, }, ] const output = detectPrerenderRoutes() expectPresence(output, { name: 'tasks', path: '/tasks', filePath: '/mocked_path/tasks', }) expectPresence(output, { name: 'kittens', path: '/kittens', filePath: '/mocked_path/Kittens.tsx', }) }) })
5,721
0
petrpan-code/redwoodjs/redwood/packages/prerender/src/babelPlugins
petrpan-code/redwoodjs/redwood/packages/prerender/src/babelPlugins/__tests__/babel-plugin-redwood-prerender-media-imports.test.ts
import path from 'path' import pluginTester from 'babel-plugin-tester' import { BundlerEnum } from '@redwoodjs/project-config' import plugin from '../babel-plugin-redwood-prerender-media-imports' let mockDistDir let mockSrcDir jest.mock('@redwoodjs/project-config', () => { return { ...jest.requireActual('@redwoodjs/project-config'), getPaths: () => { return { web: { dist: mockDistDir, src: mockSrcDir, }, } }, } }) jest.mock('../utils', () => { return { convertToDataUrl: (assetPath) => { return `data:image/jpg;base64,xxx-mock-b64-${assetPath}` }, } }) describe('Webpack bundler', () => { beforeEach(() => { mockDistDir = path.resolve(__dirname, './__fixtures__/webpackDistDir') mockSrcDir = path.resolve(__dirname, './__fixtures__/webpackSrcDir') }) describe('Should replace larger imports based on generated manifest', () => { pluginTester({ plugin, pluginName: 'babel-plugin-redwood-prerender-media-imports', pluginOptions: { bundler: BundlerEnum.WEBPACK, }, tests: [ { title: 'Handle jpgs', code: `import img1 from './image1.jpg'`, output: `const img1 = '/static/media/myImageOne.hash.jpg'`, }, { title: 'Handle jpegs', code: `import img2 from './image2.jpeg'`, output: `const img2 = '/static/media/myImageTwo.hash.jpeg'`, }, { title: 'Handle pngs', code: `import img3 from './image3.png'`, output: `const img3 = '/static/media/myImageThree.hash.png'`, }, { title: 'Handle bmps', code: `import img4 from './image4.bmp'`, output: `const img4 = '/static/media/myImageFour.hash.bmp'`, }, { title: 'Handle pdfs', code: `import pdfDoc from './terms.pdf'`, output: `const pdfDoc = '/static/media/terms.pdf'`, }, { title: 'Handle gifs', code: `import nyanCat from './nyan.gif'`, output: `const nyanCat = '/static/media/nyanKitty.gif'`, }, ], }) afterAll(() => { jest.clearAllMocks() }) }) describe('Should replace small img sources with blank data url', () => { // These imports aren't in the manifest // which simulates that they were handled by the url loader pluginTester({ plugin, // disable formatter for this test formatResult: (r) => r, pluginName: 'babel-plugin-redwood-prerender-media-imports', pluginOptions: { bundler: BundlerEnum.WEBPACK, }, tests: [ { title: 'Url loaded image', code: `import img1 from './small.jpg'`, output: `const img1 = "data:image/jpg;base64,xxx-mock-b64-small.jpg";`, }, ], }) afterAll(() => { jest.clearAllMocks() }) }) }) describe('Vite bundler', () => { beforeEach(() => { mockDistDir = path.resolve(__dirname, './__fixtures__/viteDistDir') mockSrcDir = path.resolve(__dirname, './__fixtures__/viteSrcDir') }) describe('Should replace larger imports based on generated manifest', () => { pluginTester({ plugin, pluginName: 'babel-plugin-redwood-prerender-media-imports', pluginOptions: { bundler: BundlerEnum.VITE, }, filepath: path.resolve( __dirname, './__fixtures__/viteSrcDir/pages/HomePage/HomePage.js' ), tests: [ { title: 'Handle jpgs', code: `import img1 from '../../components/Post/Posts/image1.jpg'`, output: `const img1 = 'assets/image1-hash.jpg'`, }, { title: 'Handle jpegs', code: `import img2 from './image2.jpeg'`, output: `const img2 = 'assets/image2-hash.jpeg'`, }, { title: 'Handle pngs', code: `import img3 from './image3.png'`, output: `const img3 = 'assets/image3-hash.png'`, }, { title: 'Handle bmps', code: `import img4 from './image4.bmp'`, output: `const img4 = 'assets/image4-hash.bmp'`, }, { title: 'Handle pdfs', code: `import pdfDoc from '../../pdf/invoice.pdf'`, output: `const pdfDoc = 'assets/invoice-7d64ed28.pdf'`, }, { title: 'Handle gifs', code: `import nyanCat from './funny.gif'`, output: `const nyanCat = 'assets/funny-hash.gif'`, }, ], }) afterAll(() => { jest.clearAllMocks() }) }) describe('Should replace small img sources with blank data url', () => { // These imports aren't in the manifest // which simulates that they were handled by the url loader pluginTester({ plugin, // disable formatter for this test formatResult: (r) => r, pluginName: 'babel-plugin-redwood-prerender-media-imports', pluginOptions: { bundler: BundlerEnum.VITE, }, filepath: path.resolve( __dirname, './__fixtures__/viteSrcDir/pages/HomePage/HomePage.js' ), tests: [ { title: 'Url loaded image', code: `import img1 from './small.jpg'`, output: `const img1 = "data:image/jpg;base64,xxx-mock-b64-small.jpg";`, }, ], }) afterAll(() => { jest.clearAllMocks() }) }) })
5,740
0
petrpan-code/redwoodjs/redwood/packages/project-config/src
petrpan-code/redwoodjs/redwood/packages/project-config/src/__tests__/config.test.ts
import path from 'path' import { getConfig, getRawConfig } from '../config' describe('getRawConfig', () => { it('returns nothing for an empty config', () => { const config = getRawConfig( path.join(__dirname, './fixtures/redwood.empty.toml') ) expect(config).toMatchInlineSnapshot(`{}`) }) it('returns only the defined values', () => { const config = getRawConfig(path.join(__dirname, './fixtures/redwood.toml')) expect(config).toMatchInlineSnapshot(` { "web": { "port": 8888, }, } `) }) }) describe('getConfig', () => { it('returns a default config', () => { const config = getConfig( path.join(__dirname, './fixtures/redwood.empty.toml') ) expect(config).toMatchInlineSnapshot(` { "api": { "debugPort": 18911, "host": "localhost", "path": "./api", "port": 8911, "schemaPath": "./api/db/schema.prisma", "serverConfig": "./api/server.config.js", "target": "node", "title": "Redwood App", }, "browser": { "open": false, }, "experimental": { "cli": { "autoInstall": true, "plugins": [ { "package": "@redwoodjs/cli-storybook", }, { "package": "@redwoodjs/cli-data-migrate", }, ], }, "opentelemetry": { "apiSdk": undefined, "enabled": false, "wrapApi": true, }, "realtime": { "enabled": false, }, "rsc": { "enabled": false, }, "streamingSsr": { "enabled": false, }, "studio": { "graphiql": { "authImpersonation": { "authProvider": undefined, "email": undefined, "jwtSecret": "secret", "roles": undefined, "userId": undefined, }, "endpoint": "graphql", }, "inMemory": false, }, "useSDLCodeGenForGraphQLTypes": false, }, "generate": { "nestScaffoldByModel": true, "stories": true, "tests": true, }, "graphql": { "fragments": false, "trustedDocuments": false, }, "notifications": { "versionUpdates": [], }, "web": { "a11y": true, "apiUrl": "/.redwood/functions", "bundler": "vite", "fastRefresh": true, "host": "localhost", "includeEnvironmentVariables": [], "path": "./web", "port": 8910, "sourceMap": false, "target": "browser", "title": "Redwood App", }, } `) }) it('merges configs', () => { const config = getConfig(path.join(__dirname, './fixtures/redwood.toml')) expect(config.web.port).toEqual(8888) expect(config.experimental.studio.inMemory).toEqual(false) expect(config.experimental.studio.graphiql?.endpoint).toEqual('graphql') }) describe('with studio configs', () => { it('merges studio configs', () => { const config = getConfig( path.join(__dirname, './fixtures/redwood.studio.toml') ) expect(config.experimental.studio.inMemory).toEqual(false) expect(config.experimental.studio.graphiql?.endpoint).toEqual( 'graphql-endpoint' ) }) it('merges studio configs with dbAuth impersonation', () => { const config = getConfig( path.join(__dirname, './fixtures/redwood.studio.dbauth.toml') ) expect(config.experimental.studio.inMemory).toEqual(false) expect(config.experimental.studio.graphiql?.endpoint).toEqual('graphql') expect( config.experimental.studio.graphiql?.authImpersonation?.authProvider ).toEqual('dbAuth') expect( config.experimental.studio.graphiql?.authImpersonation?.email ).toEqual('[email protected]') expect( config.experimental.studio.graphiql?.authImpersonation?.userId ).toEqual('1') }) it('merges studio configs with supabase impersonation', () => { const config = getConfig( path.join(__dirname, './fixtures/redwood.studio.supabase.toml') ) expect(config.experimental.studio.inMemory).toEqual(false) expect(config.experimental.studio.graphiql?.endpoint).toEqual('graphql') expect( config.experimental.studio.graphiql?.authImpersonation?.authProvider ).toEqual('supabase') expect( config.experimental.studio.graphiql?.authImpersonation?.email ).toEqual('[email protected]') expect( config.experimental.studio.graphiql?.authImpersonation?.userId ).toEqual('1') expect( config.experimental.studio.graphiql?.authImpersonation?.jwtSecret ).toEqual('supa-secret') }) }) describe('with graphql configs', () => { describe('sets defaults', () => { it('sets trustedDocuments to false', () => { const config = getConfig( path.join(__dirname, './fixtures/redwood.toml') ) expect(config.graphql.trustedDocuments).toEqual(false) expect(config.graphql.fragments).toEqual(false) }) }) it('merges graphql configs', () => { const config = getConfig( path.join(__dirname, './fixtures/redwood.graphql.toml') ) expect(config.graphql.trustedDocuments).toEqual(true) expect(config.graphql.fragments).toEqual(true) }) }) it('throws an error when given a bad config path', () => { const runGetConfig = () => { getConfig(path.join(__dirname, './fixtures/fake_redwood.toml')) } expect(runGetConfig).toThrow( /Could not parse .+fake_redwood.toml.+ Error: ENOENT: no such file or directory, open .+fake_redwood.toml./ ) }) it('interpolates environment variables correctly', () => { process.env.API_URL = '/bazinga' process.env.APP_ENV = 'staging' const config = getConfig( path.join(__dirname, './fixtures/redwood.withEnv.toml') ) // Fallsback to the default if env var not supplied expect(config.web.port).toBe('8910') // remember env vars have to be strings // Uses the env var if supplied expect(config.web.apiUrl).toBe('/bazinga') expect(config.web.title).toBe('App running on staging') delete process.env.API_URL delete process.env.APP_ENV }) })
5,741
0
petrpan-code/redwoodjs/redwood/packages/project-config/src
petrpan-code/redwoodjs/redwood/packages/project-config/src/__tests__/paths.test.ts
import path from 'path' import { processPagesDir, resolveFile, ensurePosixPath, importStatementPath, getBaseDir, getBaseDirFromFile, getPaths, } from '../paths' const RWJS_CWD = process.env.RWJS_CWD describe('paths', () => { describe('within empty project', () => { const FIXTURE_BASEDIR = path.join( __dirname, '..', '..', '..', '..', '__fixtures__', 'empty-project' ) beforeAll(() => { process.env.RWJS_CWD = FIXTURE_BASEDIR }) afterAll(() => { process.env.RWJS_CWD = RWJS_CWD }) it('finds the correct base directory', () => { expect(getBaseDir()).toBe(FIXTURE_BASEDIR) }) it('finds the correct base directory from a file', () => { const projectFilePath = path.join( FIXTURE_BASEDIR, 'web', 'src', 'pages', 'AboutPage' ) expect(getBaseDirFromFile(projectFilePath)).toBe(FIXTURE_BASEDIR) }) it('gets the correct paths', () => { const expectedPaths = { base: FIXTURE_BASEDIR, generated: { base: path.join(FIXTURE_BASEDIR, '.redwood'), schema: path.join(FIXTURE_BASEDIR, '.redwood', 'schema.graphql'), types: { includes: path.join( FIXTURE_BASEDIR, '.redwood', 'types', 'includes' ), mirror: path.join(FIXTURE_BASEDIR, '.redwood', 'types', 'mirror'), }, prebuild: path.join(FIXTURE_BASEDIR, '.redwood', 'prebuild'), }, scripts: path.join(FIXTURE_BASEDIR, 'scripts'), api: { base: path.join(FIXTURE_BASEDIR, 'api'), dataMigrations: path.join( FIXTURE_BASEDIR, 'api', 'db', 'dataMigrations' ), db: path.join(FIXTURE_BASEDIR, 'api', 'db'), dbSchema: path.join(FIXTURE_BASEDIR, 'api', 'db', 'schema.prisma'), functions: path.join(FIXTURE_BASEDIR, 'api', 'src', 'functions'), graphql: path.join(FIXTURE_BASEDIR, 'api', 'src', 'graphql'), lib: path.join(FIXTURE_BASEDIR, 'api', 'src', 'lib'), generators: path.join(FIXTURE_BASEDIR, 'api', 'generators'), config: path.join(FIXTURE_BASEDIR, 'api', 'src', 'config'), services: path.join(FIXTURE_BASEDIR, 'api', 'src', 'services'), directives: path.join(FIXTURE_BASEDIR, 'api', 'src', 'directives'), subscriptions: path.join( FIXTURE_BASEDIR, 'api', 'src', 'subscriptions' ), src: path.join(FIXTURE_BASEDIR, 'api', 'src'), dist: path.join(FIXTURE_BASEDIR, 'api', 'dist'), types: path.join(FIXTURE_BASEDIR, 'api', 'types'), models: path.join(FIXTURE_BASEDIR, 'api', 'src', 'models'), mail: path.join(FIXTURE_BASEDIR, 'api', 'src', 'mail'), }, web: { routes: path.join(FIXTURE_BASEDIR, 'web', 'src', 'Routes.tsx'), routeManifest: path.join( FIXTURE_BASEDIR, 'web', 'dist', 'server', 'route-manifest.json' ), base: path.join(FIXTURE_BASEDIR, 'web'), pages: path.join(FIXTURE_BASEDIR, 'web', 'src', 'pages/'), components: path.join(FIXTURE_BASEDIR, 'web', 'src', 'components'), layouts: path.join(FIXTURE_BASEDIR, 'web', 'src', 'layouts/'), src: path.join(FIXTURE_BASEDIR, 'web', 'src'), generators: path.join(FIXTURE_BASEDIR, 'web', 'generators'), document: null, // this fixture doesnt have a document app: path.join(FIXTURE_BASEDIR, 'web', 'src', 'App.tsx'), index: null, html: path.join(FIXTURE_BASEDIR, 'web', 'src', 'index.html'), config: path.join(FIXTURE_BASEDIR, 'web', 'config'), webpack: path.join( FIXTURE_BASEDIR, 'web', 'config', 'webpack.config.js' ), postcss: path.join( FIXTURE_BASEDIR, 'web', 'config', 'postcss.config.js' ), storybookConfig: path.join( FIXTURE_BASEDIR, 'web', 'config', 'storybook.config.js' ), storybookPreviewConfig: path.join( FIXTURE_BASEDIR, 'web', 'config', 'storybook.preview.js' ), storybookManagerConfig: path.join( FIXTURE_BASEDIR, 'web', 'config', 'storybook.manager.js' ), dist: path.join(FIXTURE_BASEDIR, 'web', 'dist'), distEntryServer: path.join( FIXTURE_BASEDIR, 'web', 'dist', 'server', 'entry.server.js' ), distRouteHooks: path.join( FIXTURE_BASEDIR, 'web', 'dist', 'server', 'routeHooks' ), distServer: path.join(FIXTURE_BASEDIR, 'web', 'dist', 'server'), distDocumentServer: path.join( FIXTURE_BASEDIR, 'web', 'dist', 'server', 'Document.js' ), distServerEntries: path.join( FIXTURE_BASEDIR, 'web', 'dist', 'server', 'entries.js' ), types: path.join(FIXTURE_BASEDIR, 'web', 'types'), // Vite paths ~ not configured in empty-project viteConfig: null, entryClient: null, entryServer: null, entries: null, graphql: path.join(FIXTURE_BASEDIR, 'web', 'src', 'graphql'), }, } const paths = getPaths() expect(paths).toStrictEqual(expectedPaths) }) it('switches windows slashes in import statements', () => { const originalPlatform = process.platform Object.defineProperty(process, 'platform', { value: 'win32', }) const inputPath = 'C:\\Users\\Bob\\dev\\Redwood\\UserPage\\UserPage' const outputPath = importStatementPath(inputPath) Object.defineProperty(process, 'platform', { value: originalPlatform, }) expect(outputPath).toEqual('C:/Users/Bob/dev/Redwood/UserPage/UserPage') }) describe('processPagesDir', () => { it('it accurately finds and names the pages', () => { const pagesDir = path.join(FIXTURE_BASEDIR, 'web', 'src', 'pages') const pages = processPagesDir(pagesDir) expect(pages.length).toEqual(2) const fatalErrorPage = pages.find( (page) => page.importName === 'FatalErrorPage' ) expect(fatalErrorPage).not.toBeUndefined() expect(fatalErrorPage.importPath).toEqual( importStatementPath( path.join(pagesDir, 'FatalErrorPage/FatalErrorPage') ) ) const notFoundPage = pages.find( (page) => page.importName === 'NotFoundPage' ) expect(notFoundPage).not.toBeUndefined() expect(notFoundPage.importPath).toEqual( importStatementPath(path.join(pagesDir, 'NotFoundPage/NotFoundPage')) ) }) }) describe('resolveFile', () => { const p = resolveFile(path.join(FIXTURE_BASEDIR, 'web', 'src', 'App')) expect(path.extname(p)).toEqual('.tsx') const q = resolveFile( path.join(FIXTURE_BASEDIR, 'web', 'public', 'favicon') ) expect(q).toBe(null) }) describe('ensurePosixPath', () => { it('Returns unmodified input if not on Windows', () => { const originalPlatform = process.platform Object.defineProperty(process, 'platform', { value: 'NotWindows', }) const testPath = 'X:\\some\\weird\\path' const posixPath = ensurePosixPath(testPath) Object.defineProperty(process, 'platform', { value: originalPlatform, }) expect(posixPath).toEqual(testPath) }) it('Transforms paths on Windows', () => { const originalPlatform = process.platform Object.defineProperty(process, 'platform', { value: 'win32', }) const testPath = '..\\some\\relative\\path' const posixPath = ensurePosixPath(testPath) Object.defineProperty(process, 'platform', { value: originalPlatform, }) expect(posixPath).toEqual('../some/relative/path') }) it('Handles drive letters', () => { const originalPlatform = process.platform Object.defineProperty(process, 'platform', { value: 'win32', }) const testPath = 'C:\\some\\full\\path\\to\\file.ext' const posixPath = ensurePosixPath(testPath) Object.defineProperty(process, 'platform', { value: originalPlatform, }) expect(posixPath).toEqual('/c/some/full/path/to/file.ext') }) }) }) describe('within example-todo-main project', () => { const FIXTURE_BASEDIR = path.join( __dirname, '..', '..', '..', '..', '__fixtures__', 'example-todo-main' ) beforeAll(() => { process.env.RWJS_CWD = FIXTURE_BASEDIR }) afterAll(() => { process.env.RWJS_CWD = RWJS_CWD }) it('finds the correct base directory', () => { expect(getBaseDir()).toBe(FIXTURE_BASEDIR) }) it('finds the correct base directory from a file', () => { const projectFilePath = path.join( FIXTURE_BASEDIR, 'web', 'src', 'pages', 'AboutPage' ) expect(getBaseDirFromFile(projectFilePath)).toBe(FIXTURE_BASEDIR) }) it('gets the correct paths', () => { const expectedPaths = { base: FIXTURE_BASEDIR, generated: { base: path.join(FIXTURE_BASEDIR, '.redwood'), schema: path.join(FIXTURE_BASEDIR, '.redwood', 'schema.graphql'), types: { includes: path.join( FIXTURE_BASEDIR, '.redwood', 'types', 'includes' ), mirror: path.join(FIXTURE_BASEDIR, '.redwood', 'types', 'mirror'), }, prebuild: path.join(FIXTURE_BASEDIR, '.redwood', 'prebuild'), }, scripts: path.join(FIXTURE_BASEDIR, 'scripts'), api: { base: path.join(FIXTURE_BASEDIR, 'api'), dataMigrations: path.join( FIXTURE_BASEDIR, 'api', 'db', 'dataMigrations' ), db: path.join(FIXTURE_BASEDIR, 'api', 'db'), dbSchema: path.join(FIXTURE_BASEDIR, 'api', 'db', 'schema.prisma'), functions: path.join(FIXTURE_BASEDIR, 'api', 'src', 'functions'), graphql: path.join(FIXTURE_BASEDIR, 'api', 'src', 'graphql'), lib: path.join(FIXTURE_BASEDIR, 'api', 'src', 'lib'), generators: path.join(FIXTURE_BASEDIR, 'api', 'generators'), config: path.join(FIXTURE_BASEDIR, 'api', 'src', 'config'), services: path.join(FIXTURE_BASEDIR, 'api', 'src', 'services'), directives: path.join(FIXTURE_BASEDIR, 'api', 'src', 'directives'), subscriptions: path.join( FIXTURE_BASEDIR, 'api', 'src', 'subscriptions' ), src: path.join(FIXTURE_BASEDIR, 'api', 'src'), dist: path.join(FIXTURE_BASEDIR, 'api', 'dist'), types: path.join(FIXTURE_BASEDIR, 'api', 'types'), models: path.join(FIXTURE_BASEDIR, 'api', 'src', 'models'), mail: path.join(FIXTURE_BASEDIR, 'api', 'src', 'mail'), }, web: { routes: path.join(FIXTURE_BASEDIR, 'web', 'src', 'Routes.js'), routeManifest: path.join( FIXTURE_BASEDIR, 'web', 'dist', 'server', 'route-manifest.json' ), base: path.join(FIXTURE_BASEDIR, 'web'), pages: path.join(FIXTURE_BASEDIR, 'web', 'src', 'pages/'), components: path.join(FIXTURE_BASEDIR, 'web', 'src', 'components'), layouts: path.join(FIXTURE_BASEDIR, 'web', 'src', 'layouts/'), src: path.join(FIXTURE_BASEDIR, 'web', 'src'), generators: path.join(FIXTURE_BASEDIR, 'web', 'generators'), app: path.join(FIXTURE_BASEDIR, 'web', 'src', 'App.js'), document: null, // this fixture doesnt have a document index: null, html: path.join(FIXTURE_BASEDIR, 'web', 'src', 'index.html'), config: path.join(FIXTURE_BASEDIR, 'web', 'config'), webpack: path.join( FIXTURE_BASEDIR, 'web', 'config', 'webpack.config.js' ), postcss: path.join( FIXTURE_BASEDIR, 'web', 'config', 'postcss.config.js' ), storybookConfig: path.join( FIXTURE_BASEDIR, 'web', 'config', 'storybook.config.js' ), storybookPreviewConfig: path.join( FIXTURE_BASEDIR, 'web', 'config', 'storybook.preview.js' ), storybookManagerConfig: path.join( FIXTURE_BASEDIR, 'web', 'config', 'storybook.manager.js' ), dist: path.join(FIXTURE_BASEDIR, 'web', 'dist'), distEntryServer: path.join( FIXTURE_BASEDIR, 'web', 'dist', 'server', 'entry.server.js' ), distDocumentServer: path.join( FIXTURE_BASEDIR, 'web', 'dist', 'server', 'Document.js' ), distRouteHooks: path.join( FIXTURE_BASEDIR, 'web', 'dist', 'server', 'routeHooks' ), distServer: path.join(FIXTURE_BASEDIR, 'web', 'dist', 'server'), distServerEntries: path.join( FIXTURE_BASEDIR, 'web', 'dist', 'server', 'entries.js' ), types: path.join(FIXTURE_BASEDIR, 'web', 'types'), graphql: path.join(FIXTURE_BASEDIR, 'web', 'src', 'graphql'), // New Vite paths viteConfig: path.join(FIXTURE_BASEDIR, 'web', 'vite.config.ts'), entryClient: null, // doesn't exist in example-todo-main entryServer: null, // doesn't exist in example-todo-main entries: null, // doesn't exist in example-todo-main }, } const paths = getPaths() expect(paths).toStrictEqual(expectedPaths) }) it('switches windows slashes in import statements', () => { const originalPlatform = process.platform Object.defineProperty(process, 'platform', { value: 'win32', }) const inputPath = 'C:\\Users\\Bob\\dev\\Redwood\\UserPage\\UserPage' const outputPath = importStatementPath(inputPath) Object.defineProperty(process, 'platform', { value: originalPlatform, }) expect(outputPath).toEqual('C:/Users/Bob/dev/Redwood/UserPage/UserPage') }) describe('processPagesDir', () => { it('it accurately finds and names the pages', () => { const pagesDir = path.join(FIXTURE_BASEDIR, 'web', 'src', 'pages') const pages = processPagesDir(pagesDir) expect(pages.length).toEqual(8) const adminEditUserPage = pages.find( (page) => page.importName === 'adminEditUserPage' ) expect(adminEditUserPage).not.toBeUndefined() expect(adminEditUserPage.importPath).toEqual( importStatementPath( path.join(pagesDir, 'admin/EditUserPage/EditUserPage') ) ) const barPage = pages.find((page) => page.importName === 'BarPage') expect(barPage).not.toBeUndefined() expect(barPage.importPath).toEqual( importStatementPath(path.join(pagesDir, 'BarPage/BarPage')) ) const fatalErrorPage = pages.find( (page) => page.importName === 'FatalErrorPage' ) expect(fatalErrorPage).not.toBeUndefined() expect(fatalErrorPage.importPath).toEqual( importStatementPath( path.join(pagesDir, 'FatalErrorPage/FatalErrorPage') ) ) const fooPage = pages.find((page) => page.importName === 'FooPage') expect(fooPage).not.toBeUndefined() expect(fooPage.importPath).toEqual( importStatementPath(path.join(pagesDir, 'FooPage/FooPage')) ) const homePage = pages.find((page) => page.importName === 'HomePage') expect(homePage).not.toBeUndefined() expect(homePage.importPath).toEqual( importStatementPath(path.join(pagesDir, 'HomePage/HomePage')) ) const notFoundPage = pages.find( (page) => page.importName === 'NotFoundPage' ) expect(notFoundPage).not.toBeUndefined() expect(notFoundPage.importPath).toEqual( importStatementPath(path.join(pagesDir, 'NotFoundPage/NotFoundPage')) ) const typeScriptPage = pages.find( (page) => page.importName === 'TypeScriptPage' ) expect(typeScriptPage).not.toBeUndefined() expect(typeScriptPage.importPath).toEqual( importStatementPath( path.join(pagesDir, 'TypeScriptPage/TypeScriptPage') ) ) const privatePage = pages.find( (page) => page.importName === 'PrivatePage' ) expect(privatePage).not.toBeUndefined() expect(privatePage.importPath).toEqual( importStatementPath(path.join(pagesDir, 'PrivatePage/PrivatePage')) ) }) }) describe('resolveFile', () => { const p = resolveFile(path.join(FIXTURE_BASEDIR, 'web', 'src', 'App')) expect(path.extname(p)).toEqual('.js') const q = resolveFile( path.join(FIXTURE_BASEDIR, 'web', 'public', 'favicon') ) expect(q).toBe(null) }) describe('ensurePosixPath', () => { it('Returns unmodified input if not on Windows', () => { const originalPlatform = process.platform Object.defineProperty(process, 'platform', { value: 'NotWindows', }) const testPath = 'X:\\some\\weird\\path' const posixPath = ensurePosixPath(testPath) Object.defineProperty(process, 'platform', { value: originalPlatform, }) expect(posixPath).toEqual(testPath) }) it('Transforms paths on Windows', () => { const originalPlatform = process.platform Object.defineProperty(process, 'platform', { value: 'win32', }) const testPath = '..\\some\\relative\\path' const posixPath = ensurePosixPath(testPath) Object.defineProperty(process, 'platform', { value: originalPlatform, }) expect(posixPath).toEqual('../some/relative/path') }) it('Handles drive letters', () => { const originalPlatform = process.platform Object.defineProperty(process, 'platform', { value: 'win32', }) const testPath = 'C:\\some\\full\\path\\to\\file.ext' const posixPath = ensurePosixPath(testPath) Object.defineProperty(process, 'platform', { value: originalPlatform, }) expect(posixPath).toEqual('/c/some/full/path/to/file.ext') }) }) }) describe('within example-todo-main-with-errors project', () => { const FIXTURE_BASEDIR = path.join( __dirname, '..', '..', '..', '..', '__fixtures__', 'example-todo-main-with-errors' ) beforeAll(() => { process.env.RWJS_CWD = FIXTURE_BASEDIR }) afterAll(() => { process.env.RWJS_CWD = RWJS_CWD }) it('finds the correct base directory', () => { expect(getBaseDir()).toBe(FIXTURE_BASEDIR) }) it('finds the correct base directory from a file', () => { const projectFilePath = path.join( FIXTURE_BASEDIR, 'web', 'src', 'pages', 'AboutPage' ) expect(getBaseDirFromFile(projectFilePath)).toBe(FIXTURE_BASEDIR) }) it('gets the correct paths', () => { const expectedPaths = { base: FIXTURE_BASEDIR, generated: { base: path.join(FIXTURE_BASEDIR, '.redwood'), schema: path.join(FIXTURE_BASEDIR, '.redwood', 'schema.graphql'), types: { includes: path.join( FIXTURE_BASEDIR, '.redwood', 'types', 'includes' ), mirror: path.join(FIXTURE_BASEDIR, '.redwood', 'types', 'mirror'), }, prebuild: path.join(FIXTURE_BASEDIR, '.redwood', 'prebuild'), }, scripts: path.join(FIXTURE_BASEDIR, 'scripts'), api: { base: path.join(FIXTURE_BASEDIR, 'api'), dataMigrations: path.join( FIXTURE_BASEDIR, 'api', 'db', 'dataMigrations' ), db: path.join(FIXTURE_BASEDIR, 'api', 'db'), dbSchema: path.join(FIXTURE_BASEDIR, 'api', 'db', 'schema.prisma'), functions: path.join(FIXTURE_BASEDIR, 'api', 'src', 'functions'), graphql: path.join(FIXTURE_BASEDIR, 'api', 'src', 'graphql'), lib: path.join(FIXTURE_BASEDIR, 'api', 'src', 'lib'), generators: path.join(FIXTURE_BASEDIR, 'api', 'generators'), config: path.join(FIXTURE_BASEDIR, 'api', 'src', 'config'), services: path.join(FIXTURE_BASEDIR, 'api', 'src', 'services'), directives: path.join(FIXTURE_BASEDIR, 'api', 'src', 'directives'), subscriptions: path.join( FIXTURE_BASEDIR, 'api', 'src', 'subscriptions' ), src: path.join(FIXTURE_BASEDIR, 'api', 'src'), dist: path.join(FIXTURE_BASEDIR, 'api', 'dist'), types: path.join(FIXTURE_BASEDIR, 'api', 'types'), models: path.join(FIXTURE_BASEDIR, 'api', 'src', 'models'), mail: path.join(FIXTURE_BASEDIR, 'api', 'src', 'mail'), }, web: { routes: path.join(FIXTURE_BASEDIR, 'web', 'src', 'Routes.js'), routeManifest: path.join( FIXTURE_BASEDIR, 'web', 'dist', 'server', 'route-manifest.json' ), base: path.join(FIXTURE_BASEDIR, 'web'), pages: path.join(FIXTURE_BASEDIR, 'web', 'src', 'pages/'), components: path.join(FIXTURE_BASEDIR, 'web', 'src', 'components'), layouts: path.join(FIXTURE_BASEDIR, 'web', 'src', 'layouts/'), src: path.join(FIXTURE_BASEDIR, 'web', 'src'), document: null, // this fixture doesnt have a document generators: path.join(FIXTURE_BASEDIR, 'web', 'generators'), app: null, index: path.join(FIXTURE_BASEDIR, 'web', 'src', 'index.js'), html: path.join(FIXTURE_BASEDIR, 'web', 'src', 'index.html'), config: path.join(FIXTURE_BASEDIR, 'web', 'config'), webpack: path.join( FIXTURE_BASEDIR, 'web', 'config', 'webpack.config.js' ), viteConfig: null, // no vite config in example-todo-main-with-errors postcss: path.join( FIXTURE_BASEDIR, 'web', 'config', 'postcss.config.js' ), storybookConfig: path.join( FIXTURE_BASEDIR, 'web', 'config', 'storybook.config.js' ), storybookPreviewConfig: path.join( FIXTURE_BASEDIR, 'web', 'config', 'storybook.preview.js' ), storybookManagerConfig: path.join( FIXTURE_BASEDIR, 'web', 'config', 'storybook.manager.js' ), entryClient: null, entryServer: null, entries: null, dist: path.join(FIXTURE_BASEDIR, 'web', 'dist'), distEntryServer: path.join( FIXTURE_BASEDIR, 'web', 'dist', 'server', 'entry.server.js' ), distDocumentServer: path.join( FIXTURE_BASEDIR, 'web', 'dist', 'server', 'Document.js' ), // this is constructed regardless of presence of src/Document distRouteHooks: path.join( FIXTURE_BASEDIR, 'web', 'dist', 'server', 'routeHooks' ), distServer: path.join(FIXTURE_BASEDIR, 'web', 'dist', 'server'), distServerEntries: path.join( FIXTURE_BASEDIR, 'web', 'dist', 'server', 'entries.js' ), types: path.join(FIXTURE_BASEDIR, 'web', 'types'), graphql: path.join(FIXTURE_BASEDIR, 'web', 'src', 'graphql'), }, } const paths = getPaths() expect(paths).toStrictEqual(expectedPaths) }) it('switches windows slashes in import statements', () => { const originalPlatform = process.platform Object.defineProperty(process, 'platform', { value: 'win32', }) const inputPath = 'C:\\Users\\Bob\\dev\\Redwood\\UserPage\\UserPage' const outputPath = importStatementPath(inputPath) Object.defineProperty(process, 'platform', { value: originalPlatform, }) expect(outputPath).toEqual('C:/Users/Bob/dev/Redwood/UserPage/UserPage') }) describe('processPagesDir', () => { it('it accurately finds and names the pages', () => { const pagesDir = path.join(FIXTURE_BASEDIR, 'web', 'src', 'pages') const pages = processPagesDir(pagesDir) expect(pages.length).toEqual(3) const fatalErrorPage = pages.find( (page) => page.importName === 'FatalErrorPage' ) expect(fatalErrorPage).not.toBeUndefined() expect(fatalErrorPage.importPath).toEqual( importStatementPath( path.join(pagesDir, 'FatalErrorPage/FatalErrorPage') ) ) const homePage = pages.find((page) => page.importName === 'HomePage') expect(homePage).not.toBeUndefined() expect(homePage.importPath).toEqual( importStatementPath(path.join(pagesDir, 'HomePage/HomePage')) ) const notFoundPage = pages.find( (page) => page.importName === 'NotFoundPage' ) expect(notFoundPage).not.toBeUndefined() expect(notFoundPage.importPath).toEqual( importStatementPath(path.join(pagesDir, 'NotFoundPage/NotFoundPage')) ) }) }) describe('resolveFile', () => { const p = resolveFile(path.join(FIXTURE_BASEDIR, 'web', 'src', 'index')) expect(path.extname(p)).toEqual('.js') const q = resolveFile( path.join(FIXTURE_BASEDIR, 'web', 'public', 'favicon') ) expect(q).toBe(null) }) describe('ensurePosixPath', () => { it('Returns unmodified input if not on Windows', () => { const originalPlatform = process.platform Object.defineProperty(process, 'platform', { value: 'NotWindows', }) const testPath = 'X:\\some\\weird\\path' const posixPath = ensurePosixPath(testPath) Object.defineProperty(process, 'platform', { value: originalPlatform, }) expect(posixPath).toEqual(testPath) }) it('Transforms paths on Windows', () => { const originalPlatform = process.platform Object.defineProperty(process, 'platform', { value: 'win32', }) const testPath = '..\\some\\relative\\path' const posixPath = ensurePosixPath(testPath) Object.defineProperty(process, 'platform', { value: originalPlatform, }) expect(posixPath).toEqual('../some/relative/path') }) it('Handles drive letters', () => { const originalPlatform = process.platform Object.defineProperty(process, 'platform', { value: 'win32', }) const testPath = 'C:\\some\\full\\path\\to\\file.ext' const posixPath = ensurePosixPath(testPath) Object.defineProperty(process, 'platform', { value: originalPlatform, }) expect(posixPath).toEqual('/c/some/full/path/to/file.ext') }) }) }) describe('within test project', () => { const FIXTURE_BASEDIR = path.join( __dirname, '..', '..', '..', '..', '__fixtures__', 'test-project' ) beforeAll(() => { process.env.RWJS_CWD = FIXTURE_BASEDIR }) afterAll(() => { process.env.RWJS_CWD = RWJS_CWD }) it('finds the correct base directory', () => { expect(getBaseDir()).toBe(FIXTURE_BASEDIR) }) it('finds the correct base directory from a file', () => { const projectFilePath = path.join( FIXTURE_BASEDIR, 'web', 'src', 'pages', 'AboutPage' ) expect(getBaseDirFromFile(projectFilePath)).toBe(FIXTURE_BASEDIR) }) it('gets the correct paths', () => { const expectedPaths = { base: FIXTURE_BASEDIR, generated: { base: path.join(FIXTURE_BASEDIR, '.redwood'), schema: path.join(FIXTURE_BASEDIR, '.redwood', 'schema.graphql'), types: { includes: path.join( FIXTURE_BASEDIR, '.redwood', 'types', 'includes' ), mirror: path.join(FIXTURE_BASEDIR, '.redwood', 'types', 'mirror'), }, prebuild: path.join(FIXTURE_BASEDIR, '.redwood', 'prebuild'), }, scripts: path.join(FIXTURE_BASEDIR, 'scripts'), api: { base: path.join(FIXTURE_BASEDIR, 'api'), dataMigrations: path.join( FIXTURE_BASEDIR, 'api', 'db', 'dataMigrations' ), db: path.join(FIXTURE_BASEDIR, 'api', 'db'), dbSchema: path.join(FIXTURE_BASEDIR, 'api', 'db', 'schema.prisma'), functions: path.join(FIXTURE_BASEDIR, 'api', 'src', 'functions'), graphql: path.join(FIXTURE_BASEDIR, 'api', 'src', 'graphql'), lib: path.join(FIXTURE_BASEDIR, 'api', 'src', 'lib'), generators: path.join(FIXTURE_BASEDIR, 'api', 'generators'), config: path.join(FIXTURE_BASEDIR, 'api', 'src', 'config'), services: path.join(FIXTURE_BASEDIR, 'api', 'src', 'services'), directives: path.join(FIXTURE_BASEDIR, 'api', 'src', 'directives'), subscriptions: path.join( FIXTURE_BASEDIR, 'api', 'src', 'subscriptions' ), src: path.join(FIXTURE_BASEDIR, 'api', 'src'), dist: path.join(FIXTURE_BASEDIR, 'api', 'dist'), types: path.join(FIXTURE_BASEDIR, 'api', 'types'), models: path.join(FIXTURE_BASEDIR, 'api', 'src', 'models'), mail: path.join(FIXTURE_BASEDIR, 'api', 'src', 'mail'), }, web: { routes: path.join(FIXTURE_BASEDIR, 'web', 'src', 'Routes.tsx'), routeManifest: path.join( FIXTURE_BASEDIR, 'web', 'dist', 'server', 'route-manifest.json' ), base: path.join(FIXTURE_BASEDIR, 'web'), pages: path.join(FIXTURE_BASEDIR, 'web', 'src', 'pages/'), components: path.join(FIXTURE_BASEDIR, 'web', 'src', 'components'), layouts: path.join(FIXTURE_BASEDIR, 'web', 'src', 'layouts/'), document: null, // this fixture doesnt have a document src: path.join(FIXTURE_BASEDIR, 'web', 'src'), generators: path.join(FIXTURE_BASEDIR, 'web', 'generators'), app: path.join(FIXTURE_BASEDIR, 'web', 'src', 'App.tsx'), index: null, html: path.join(FIXTURE_BASEDIR, 'web', 'src', 'index.html'), config: path.join(FIXTURE_BASEDIR, 'web', 'config'), webpack: path.join( FIXTURE_BASEDIR, 'web', 'config', 'webpack.config.js' ), postcss: path.join( FIXTURE_BASEDIR, 'web', 'config', 'postcss.config.js' ), storybookConfig: path.join( FIXTURE_BASEDIR, 'web', 'config', 'storybook.config.js' ), storybookPreviewConfig: path.join( FIXTURE_BASEDIR, 'web', 'config', 'storybook.preview.js' ), storybookManagerConfig: path.join( FIXTURE_BASEDIR, 'web', 'config', 'storybook.manager.js' ), dist: path.join(FIXTURE_BASEDIR, 'web', 'dist'), distEntryServer: path.join( FIXTURE_BASEDIR, 'web', 'dist', 'server', 'entry.server.js' ), distDocumentServer: path.join( FIXTURE_BASEDIR, 'web', 'dist', 'server', 'Document.js' ), distRouteHooks: path.join( FIXTURE_BASEDIR, 'web', 'dist', 'server', 'routeHooks' ), distServer: path.join(FIXTURE_BASEDIR, 'web', 'dist', 'server'), distServerEntries: path.join( FIXTURE_BASEDIR, 'web', 'dist', 'server', 'entries.js' ), types: path.join(FIXTURE_BASEDIR, 'web', 'types'), graphql: path.join(FIXTURE_BASEDIR, 'web', 'src', 'graphql'), // Vite paths viteConfig: path.join(FIXTURE_BASEDIR, 'web', 'vite.config.ts'), entryClient: path.join(FIXTURE_BASEDIR, 'web/src/entry.client.tsx'), entryServer: null, entries: null, }, } const paths = getPaths() expect(paths).toStrictEqual(expectedPaths) }) it('switches windows slashes in import statements', () => { const originalPlatform = process.platform Object.defineProperty(process, 'platform', { value: 'win32', }) const inputPath = 'C:\\Users\\Bob\\dev\\Redwood\\UserPage\\UserPage' const outputPath = importStatementPath(inputPath) Object.defineProperty(process, 'platform', { value: originalPlatform, }) expect(outputPath).toEqual('C:/Users/Bob/dev/Redwood/UserPage/UserPage') }) describe('processPagesDir', () => { it('it accurately finds and names the pages', () => { const pagesDir = path.join(FIXTURE_BASEDIR, 'web', 'src', 'pages') const pages = processPagesDir(pagesDir) expect(pages.length).toEqual(21) const pageNames = [ 'AboutPage', 'BlogPostPage', 'ContactUsPage', 'FatalErrorPage', 'ForgotPasswordPage', 'HomePage', 'LoginPage', 'NotFoundPage', 'ProfilePage', 'ResetPasswordPage', 'SignupPage', 'WaterfallPage', ] pageNames.forEach((pageName) => { const thisPage = pages.find((page) => page.importName === pageName) expect(thisPage).not.toBeUndefined() expect(thisPage.importPath).toEqual( importStatementPath(path.join(pagesDir, `${pageName}/${pageName}`)) ) }) const scaffoldPageNames = ['Contact', 'Post'] scaffoldPageNames.forEach((pageName) => { let page = pages.find( (page) => page.importName === `${pageName}Edit${pageName}Page` ) expect(page).not.toBeUndefined() expect(page.importPath).toEqual( importStatementPath( path.join( pagesDir, `${pageName}/Edit${pageName}Page/Edit${pageName}Page` ) ) ) page = pages.find( (page) => page.importName === `${pageName}New${pageName}Page` ) expect(page).not.toBeUndefined() expect(page.importPath).toEqual( importStatementPath( path.join( pagesDir, `${pageName}/New${pageName}Page/New${pageName}Page` ) ) ) page = pages.find( (page) => page.importName === `${pageName}${pageName}Page` ) expect(page).not.toBeUndefined() expect(page.importPath).toEqual( importStatementPath( path.join(pagesDir, `${pageName}/${pageName}Page/${pageName}Page`) ) ) page = pages.find( (page) => page.importName === `${pageName}${pageName}sPage` ) expect(page).not.toBeUndefined() expect(page.importPath).toEqual( importStatementPath( path.join( pagesDir, `${pageName}/${pageName}sPage/${pageName}sPage` ) ) ) }) }) }) describe('resolveFile', () => { const p = resolveFile(path.join(FIXTURE_BASEDIR, 'web', 'src', 'Routes')) expect(path.extname(p)).toEqual('.tsx') const q = resolveFile( path.join(FIXTURE_BASEDIR, 'web', 'public', 'favicon') ) expect(q).toBe(null) }) describe('ensurePosixPath', () => { it('Returns unmodified input if not on Windows', () => { const originalPlatform = process.platform Object.defineProperty(process, 'platform', { value: 'NotWindows', }) const testPath = 'X:\\some\\weird\\path' const posixPath = ensurePosixPath(testPath) Object.defineProperty(process, 'platform', { value: originalPlatform, }) expect(posixPath).toEqual(testPath) }) it('Transforms paths on Windows', () => { const originalPlatform = process.platform Object.defineProperty(process, 'platform', { value: 'win32', }) const testPath = '..\\some\\relative\\path' const posixPath = ensurePosixPath(testPath) Object.defineProperty(process, 'platform', { value: originalPlatform, }) expect(posixPath).toEqual('../some/relative/path') }) it('Handles drive letters', () => { const originalPlatform = process.platform Object.defineProperty(process, 'platform', { value: 'win32', }) const testPath = 'C:\\some\\full\\path\\to\\file.ext' const posixPath = ensurePosixPath(testPath) Object.defineProperty(process, 'platform', { value: originalPlatform, }) expect(posixPath).toEqual('/c/some/full/path/to/file.ext') }) }) }) })
5,748
0
petrpan-code/redwoodjs/redwood/packages/project-config/src/__tests__/fixtures/api
petrpan-code/redwoodjs/redwood/packages/project-config/src/__tests__/fixtures/api/test/test.ts
export const hello = ""
5,758
0
petrpan-code/redwoodjs/redwood/packages/realtime/src/graphql/plugins
petrpan-code/redwoodjs/redwood/packages/realtime/src/graphql/plugins/__tests__/useRedwoodRealtime.test.ts
import { createTestkit, createSpiedPlugin, assertStreamExecutionValue, } from '@envelop/testing' import { testQuery, testLiveQuery, testSchema } from '../__fixtures__/common' import { useRedwoodRealtime, InMemoryLiveQueryStore, } from '../useRedwoodRealtime' describe('useRedwoodRealtime', () => { it('should support a @live query directive', async () => { const testkit = createTestkit( [useRedwoodRealtime({ liveQueries: { store: 'in-memory' } })], testSchema ) const result = await testkit.execute(testLiveQuery, {}, {}) assertStreamExecutionValue(result) const current = await result.next() expect(current.value).toMatchInlineSnapshot(` { "data": { "me": { "id": "1", "name": "Ba Zinga", }, }, "isLive": true, } `) }) it('should update schema with live directive', async () => { const spiedPlugin = createSpiedPlugin() // the original schema should not have the live directive before the useRedwoodRealtime plugin is applied expect(testSchema.getDirective('live')).toBeUndefined() createTestkit( [ useRedwoodRealtime({ liveQueries: { store: 'in-memory' } }), spiedPlugin.plugin, ], testSchema ) // the replaced schema should have the live directive afterwards const replacedSchema = spiedPlugin.spies.onSchemaChange.mock.calls[0][0].schema const liveDirectiveOnSchema = replacedSchema.getDirective('live') expect(liveDirectiveOnSchema.name).toEqual('live') expect(replacedSchema.getDirective('live')).toMatchSnapshot() }) it('with live directives, it should extend the graphQL context with a store', async () => { const spiedPlugin = createSpiedPlugin() const testkit = createTestkit( [ useRedwoodRealtime({ liveQueries: { store: 'in-memory' } }), spiedPlugin.plugin, ], testSchema ) await testkit.execute(testQuery) expect(spiedPlugin.spies.beforeContextBuilding).toHaveBeenCalledTimes(1) expect(spiedPlugin.spies.beforeContextBuilding).toHaveBeenCalledWith({ context: expect.any(Object), extendContext: expect.any(Function), breakContextBuilding: expect.any(Function), }) expect(spiedPlugin.spies.afterContextBuilding).toHaveBeenCalledTimes(1) expect(spiedPlugin.spies.afterContextBuilding).toHaveBeenCalledWith({ context: expect.objectContaining({ liveQueryStore: expect.any(InMemoryLiveQueryStore), }), extendContext: expect.any(Function), }) }) it('with subscriptions, it should extend the GraphQL context with pubSub transport', async () => { const spiedPlugin = createSpiedPlugin() const testkit = createTestkit( [ useRedwoodRealtime({ subscriptions: { store: 'in-memory', subscriptions: [] }, }), spiedPlugin.plugin, ], testSchema ) await testkit.execute(testQuery) expect(spiedPlugin.spies.beforeContextBuilding).toHaveBeenCalledTimes(1) expect(spiedPlugin.spies.beforeContextBuilding).toHaveBeenCalledWith({ context: expect.any(Object), extendContext: expect.any(Function), breakContextBuilding: expect.any(Function), }) expect(spiedPlugin.spies.afterContextBuilding).toHaveBeenCalledTimes(1) expect(spiedPlugin.spies.afterContextBuilding).toHaveBeenCalledWith({ context: expect.objectContaining({ pubSub: expect.objectContaining({ publish: expect.any(Function), subscribe: expect.any(Function), }), }), extendContext: expect.any(Function), }) }) })
5,759
0
petrpan-code/redwoodjs/redwood/packages/realtime/src/graphql/plugins/__tests__
petrpan-code/redwoodjs/redwood/packages/realtime/src/graphql/plugins/__tests__/__snapshots__/useRedwoodRealtime.test.ts.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`useRedwoodRealtime should update schema with live directive 1`] = `"@live"`;
5,805
0
petrpan-code/redwoodjs/redwood/packages/router/src
petrpan-code/redwoodjs/redwood/packages/router/src/__tests__/analyzeRoutes.test.tsx
import React, { isValidElement } from 'react' import { Route, Router } from '../router' import { Private, PrivateSet, Set } from '../Set' import { analyzeRoutes } from '../util' const FakePage = () => <h1>Fake Page</h1> interface LayoutProps { children: React.ReactNode } const FakeLayout1 = ({ children }: LayoutProps) => ( <div className="layout1">{children}</div> ) const FakeLayout2 = ({ children }: LayoutProps) => ( <div className="layout2">{children}</div> ) const FakeLayout3 = ({ children }: LayoutProps) => ( <div className="layout2">{children}</div> ) describe('AnalyzeRoutes: with homePage and Children', () => { const CheckRoutes = ( <Router> <Route path="/hello" name="hello" page={FakePage} /> <Route path="/world" name="world" page={FakePage} /> <Route path="/recipe/{id}" name="recipeById" page={FakePage} /> <Route path="/" name="home" page={FakePage} /> <Route notfound page={FakePage} /> </Router> ) const { pathRouteMap, namedRoutesMap, hasHomeRoute, NotFoundPage } = analyzeRoutes(CheckRoutes.props.children, { currentPathName: '/', }) test('Should return namePathMap and hasHomeRoute correctly', () => { expect(Object.keys(pathRouteMap)).toEqual([ '/hello', '/world', '/recipe/{id}', '/', ]) expect(pathRouteMap['/hello']).toEqual( expect.objectContaining({ name: 'hello', page: FakePage, path: '/hello', }) ) expect(pathRouteMap['/world']).toEqual( expect.objectContaining({ name: 'world', page: FakePage, path: '/world', }) ) // @NOTE the path here is the path DEFINITION, not that actual path expect(pathRouteMap['/recipe/{id}']).toEqual( expect.objectContaining({ name: 'recipeById', page: FakePage, path: '/recipe/{id}', }) ) expect(hasHomeRoute).toBe(true) }) test('Should return namedRoutesMap correctly', () => { expect(namedRoutesMap.home()).toEqual('/') expect(namedRoutesMap.world()).toEqual('/world') expect(namedRoutesMap.hello({ queryGuy: 1 })).toEqual('/hello?queryGuy=1') expect(namedRoutesMap.recipeById({ id: 55 })).toEqual('/recipe/55') }) test('Should return the notFoundPage', () => { expect(NotFoundPage).toBeDefined() // @ts-expect-error We know its a valid element // We know that FakePage is an React component, and not a Spec expect(isValidElement(NotFoundPage())).toBe(true) }) test('Should return the active Route by name', () => { const { activeRoutePath } = analyzeRoutes(CheckRoutes.props.children, { currentPathName: '/recipe/512512', }) expect(activeRoutePath).toBeDefined() expect(activeRoutePath).toBe('/recipe/{id}') }) test('No home Route', () => { const CheckRoutes = ( <Router> <Route path="/iGots" name="iGots" page={FakePage} /> <Route path="/noHome" name="noHome" page={FakePage} /> </Router> ) const { pathRouteMap, namedRoutesMap, hasHomeRoute } = analyzeRoutes( CheckRoutes.props.children, { currentPathName: '/', } ) expect(Object.keys(namedRoutesMap).length).toEqual(2) expect(Object.keys(pathRouteMap).length).toEqual(2) expect(hasHomeRoute).toBe(false) }) test('Creates setWrapper map', () => { interface WrapperXProps { children: React.ReactNode id: string passThruProp: string } const WrapperX = ({ children }: WrapperXProps) => ( <> <h1>WrapperA</h1> {children} </> ) interface WrapperYProps { children: React.ReactNode id: string theme: string } const WrapperY = ({ children }: WrapperYProps) => ( <> <h1>WrapperY</h1> {children} </> ) const Simple = ( <Router> <Set wrap={[WrapperX]} id="set-one" passThruProp="bazinga"> <Route path="/a" name="routeA" page={FakePage} /> <Set wrap={[WrapperY]} id="set-two" theme="blue"> <Route name="routeB" path="/b" page={FakePage} /> <Route name="routeC" path="/c" page={FakePage} /> </Set> </Set> </Router> ) const { pathRouteMap } = analyzeRoutes(Simple.props.children, { currentPathName: '/', }) expect(pathRouteMap['/a']).toEqual( expect.objectContaining({ redirect: null, name: 'routeA', path: '/a', whileLoadingPage: undefined, sets: [ { id: '1', wrappers: [WrapperX], isPrivate: false, props: { id: 'set-one', passThruProp: 'bazinga', }, }, ], }) ) expect(pathRouteMap['/b']).toEqual( expect.objectContaining({ redirect: null, name: 'routeB', path: '/b', whileLoadingPage: undefined, sets: [ { id: '1', wrappers: [WrapperX], isPrivate: false, props: { id: 'set-one', passThruProp: 'bazinga', }, }, { id: '1.1', isPrivate: false, wrappers: [WrapperY], props: { id: 'set-two', theme: 'blue', }, }, ], }) ) expect(pathRouteMap['/c']).toEqual( expect.objectContaining({ redirect: null, name: 'routeC', path: '/c', whileLoadingPage: undefined, sets: [ { id: '1', wrappers: [WrapperX], isPrivate: false, props: { id: 'set-one', passThruProp: 'bazinga', }, }, { id: '1.1', wrappers: [WrapperY], isPrivate: false, props: { id: 'set-two', theme: 'blue', }, }, ], }) ) }) test('Connects Set wrapper props with correct Set', () => { interface WrapperXProps { children: React.ReactNode id: string passThruProp: string } const WrapperX = ({ children }: WrapperXProps) => ( <> <h1>WrapperA</h1> {children} </> ) interface WrapperYProps { children: React.ReactNode id: string theme: string } const WrapperY = ({ children }: WrapperYProps) => ( <> <h1>WrapperY</h1> {children} </> ) const Simple = ( <Router> <Set wrap={[WrapperX]} id="set-one" passThruProp="bazinga"> <Route path="/a" name="routeA" page={FakePage} /> <Set wrap={[WrapperY]} id="set-two" theme="blue"> <Route name="routeB" path="/b" page={FakePage} /> <Route name="routeC" path="/c" page={FakePage} /> </Set> </Set> </Router> ) const { pathRouteMap } = analyzeRoutes(Simple.props.children, { currentPathName: '/', }) expect(pathRouteMap['/a']).toEqual( expect.objectContaining({ redirect: null, name: 'routeA', path: '/a', whileLoadingPage: undefined, sets: [ { id: '1', wrappers: [WrapperX], isPrivate: false, props: { id: 'set-one', passThruProp: 'bazinga', }, }, ], }) ) expect(pathRouteMap['/b']).toEqual( expect.objectContaining({ redirect: null, name: 'routeB', path: '/b', whileLoadingPage: undefined, sets: [ { id: '1', wrappers: [WrapperX], isPrivate: false, props: { id: 'set-one', passThruProp: 'bazinga', }, }, { id: '1.1', wrappers: [WrapperY], isPrivate: false, props: { id: 'set-two', theme: 'blue', }, }, ], }) ) expect(pathRouteMap['/c']).toEqual( expect.objectContaining({ redirect: null, name: 'routeC', path: '/c', whileLoadingPage: undefined, sets: [ { id: '1', wrappers: [WrapperX], isPrivate: false, props: { id: 'set-one', passThruProp: 'bazinga', }, }, { id: '1.1', wrappers: [WrapperY], isPrivate: false, props: { id: 'set-two', theme: 'blue', }, }, ], }) ) }) test('Creates setWrapper map with nested sets', () => { const KrismasTree = ( <PrivateSet unauthenticated="signIn"> <Route path="/dashboard" page={FakePage} name="dashboard" /> <Set wrap={[FakeLayout1, FakeLayout2]}> <Route path="/{org}/settings/general" page={FakePage} name="settingsGeneral" /> <Route path="/{org}/settings/api" page={FakePage} name="settingsAPI" /> <Route path="/{org}/settings/twitter" page={FakePage} name="settingsTwitter" /> </Set> <Set wrap={FakeLayout1}> <Set wrap={[FakeLayout2, FakeLayout3]}> <Route path="/{org}/series" page={FakePage} name="series" /> <Route path="/{org}" page={FakePage} name="organization" /> <Route path="/account/reset-password" page={FakePage} name="resetPassword" prerender /> </Set> <Set wrap={FakeLayout2}> <Route path="/{org}/events/{eventCode}/edit" page={FakePage} name="editEvent" /> <Route path="/{org}/events/{eventCode}/players" page={FakePage} name="eventPlayers" /> <Route path="/{org}/events/{eventCode}/analytics" page={FakePage} name="eventAnalytics" /> <Route path="/{org}/events/{eventCode}/scores" page={FakePage} name="eventScores" /> <Route path="/{org}/events/{eventCode}/tweets" page={FakePage} name="eventTweets" /> </Set> </Set> </PrivateSet> ) const { pathRouteMap } = analyzeRoutes(KrismasTree.props.children, { currentPathName: '/bazingaOrg/events/kittenCode/edit', }) expect(Object.keys(pathRouteMap).length).toBe(12) // @TODO finish writing the expectations }) test('Handles Private', () => { const Routes = ( <Router> <Route path="/" name="home" page={FakePage} /> <Private unauthenticated="home"> <Route path="/private" name="privateRoute" page={FakePage} /> </Private> </Router> ) const { pathRouteMap } = analyzeRoutes(Routes.props.children, { currentPathName: '/', }) expect(pathRouteMap['/private']).toStrictEqual({ redirect: null, name: 'privateRoute', path: '/private', whileLoadingPage: undefined, page: FakePage, sets: [ { id: '1', wrappers: [], isPrivate: true, props: { unauthenticated: 'home' }, }, ], }) }) test('Handles PrivateSet', () => { const Routes = ( <Router> <Route path="/" name="home" page={FakePage} /> <PrivateSet unauthenticated="home"> <Route path="/private" name="privateRoute" page={FakePage} /> </PrivateSet> </Router> ) const { pathRouteMap } = analyzeRoutes(Routes.props.children, { currentPathName: '/', }) expect(pathRouteMap['/private']).toStrictEqual({ redirect: null, name: 'privateRoute', path: '/private', whileLoadingPage: undefined, page: FakePage, sets: [ { id: '1', wrappers: [], isPrivate: true, props: { unauthenticated: 'home' }, }, ], }) }) test('Redirect routes analysis', () => { const RedirectedRoutes = ( <Router> <Route path="/simple" redirect="/rdSimple" name="simple" /> <Route path="/rdSimple" name="rdSimple" page={() => <h1>Redirected page</h1>} /> </Router> ) const { pathRouteMap, namedRoutesMap } = analyzeRoutes( RedirectedRoutes.props.children, { currentPathName: '/simple', } ) expect(pathRouteMap['/simple'].redirect).toBe('/rdSimple') expect(pathRouteMap['/rdSimple'].redirect).toBeFalsy() // @TODO true for now, but we may not allow names on a redirect route expect(Object.keys(namedRoutesMap).length).toBe(2) expect(namedRoutesMap.simple()).toBe('/simple') expect(namedRoutesMap.rdSimple()).toBe('/rdSimple') }) test('Nested sets, and authentication logic', () => { const HomePage = () => <h1>Home Page</h1> const PrivateAdminPage = () => <h1>Private Admin Page</h1> const PrivateEmployeePage = () => <h1>Private Employee Page</h1> const PrivateNoRolesAssigned = () => <h1>Private Employee Page</h1> const RedirectedRoutes = ( <Router> <Route path="/" page={HomePage} name="home" /> <PrivateSet unauthenticated="home"> <Route path="/no-roles-assigned" page={PrivateNoRolesAssigned} name="noRolesAssigned" /> <Set private unauthenticated="noRolesAssigned" roles={['ADMIN', 'EMPLOYEE']} someProp="propFromNoRolesSet" > <PrivateSet unauthenticated="admin" roles={'EMPLOYEE'}> <Route path="/employee" page={PrivateEmployeePage} name="privateEmployee" /> </PrivateSet> <PrivateSet unauthenticated="employee" roles={'ADMIN'}> <Route path="/admin" page={PrivateAdminPage} name="privateAdmin" /> </PrivateSet> </Set> </PrivateSet> </Router> ) const { pathRouteMap, namedRoutesMap } = analyzeRoutes( RedirectedRoutes.props.children, { currentPathName: '/does-not-exist', } ) // Level 1: wrapped with private expect(pathRouteMap).toMatchObject({ '/no-roles-assigned': { redirect: null, sets: [ { id: '1', isPrivate: true, props: { unauthenticated: 'home' }, }, ], }, }) expect(Object.keys(namedRoutesMap).length).toBe(4) // Level 2: wrapped in 2 private sets expect(pathRouteMap).toMatchObject({ '/employee': { redirect: null, sets: [ { id: '1', wrappers: [], isPrivate: true, props: { unauthenticated: 'home' }, }, { id: '1.1', wrappers: [], isPrivate: true, props: expect.objectContaining({ unauthenticated: 'noRolesAssigned', roles: ['ADMIN', 'EMPLOYEE'], }), }, { id: '1.1.1', wrappers: [], isPrivate: true, props: { unauthenticated: 'admin', roles: 'EMPLOYEE', }, }, ], }, }) // Level 3: wrapped in 3 private sets expect(pathRouteMap).toMatchObject({ '/admin': { redirect: null, sets: [ // Should have the first one, but also.. { id: '1', wrappers: [], isPrivate: true, props: { unauthenticated: 'home' }, }, // ...the second private set's props { id: '1.1', wrappers: [], isPrivate: true, props: { unauthenticated: 'noRolesAssigned', roles: ['ADMIN', 'EMPLOYEE'], }, }, // ...and the third private set's props { id: '1.1.2', wrappers: [], isPrivate: true, props: { unauthenticated: 'employee', roles: 'ADMIN', }, }, ], }, }) }) }) test('Give correct ids to root sets', () => { const HomePage = () => <h1>Home Page</h1> const Page = () => <h1>Page</h1> const Layout = ({ children }: LayoutProps) => <>{children}</> const Routes = ( <Router> <Route path="/" page={HomePage} name="home" /> <Set wrap={Layout}> <Route path="/one" page={Page} name="one" /> </Set> <Set wrap={Layout}> <Route path="/two" page={Page} name="two" /> </Set> </Router> ) const { pathRouteMap } = analyzeRoutes(Routes.props.children, { currentPathName: '/', }) expect(pathRouteMap).toMatchObject({ '/': { redirect: null, sets: [], }, '/one': { redirect: null, sets: [ { id: '1', wrappers: [Layout], isPrivate: false, }, ], }, '/two': { redirect: null, sets: [ { id: '2', wrappers: [Layout], isPrivate: false, }, ], }, }) })
5,806
0
petrpan-code/redwoodjs/redwood/packages/router/src
petrpan-code/redwoodjs/redwood/packages/router/src/__tests__/history.test.tsx
import { navigate } from '../history' describe('navigate', () => { describe('does not increase history length', () => { it('handles direct matches for pathname, search, and hash', () => { expect(globalThis.history.length).toEqual(1) navigate('/test-1?search=testing#test') expect(globalThis.history.length).toEqual(2) navigate('/test-1?search=testing#test') expect(globalThis.history.length).toEqual(2) }) }) describe('increasing history length', () => { it('handles pathname', () => { expect(globalThis.history.length).toEqual(2) navigate('/test-2') expect(globalThis.history.length).toEqual(3) navigate('/test-3') expect(globalThis.history.length).toEqual(4) }) it('handles search', () => { expect(globalThis.history.length).toEqual(4) navigate('/test-3') expect(globalThis.history.length).toEqual(4) navigate('/test-3?search=testing') expect(globalThis.history.length).toEqual(5) navigate('/test-3?search=testing') expect(globalThis.history.length).toEqual(5) }) it('handles hash', () => { expect(globalThis.history.length).toEqual(5) navigate('/test-3') expect(globalThis.history.length).toEqual(6) navigate('/test-3#testing') expect(globalThis.history.length).toEqual(7) navigate('/test-3#testing') expect(globalThis.history.length).toEqual(7) }) }) })
5,807
0
petrpan-code/redwoodjs/redwood/packages/router/src
petrpan-code/redwoodjs/redwood/packages/router/src/__tests__/links.test.tsx
import React from 'react' import { toHaveClass, toHaveStyle } from '@testing-library/jest-dom/matchers' import { render } from '@testing-library/react' // TODO: Remove when jest configs are in place // @ts-expect-error - Issue with TS and jest-dom expect.extend({ toHaveClass, toHaveStyle }) import { NavLink, useMatch, Link } from '../links' import { LocationProvider } from '../location' import { flattenSearchParams } from '../util' function createDummyLocation(pathname: string, search = '') { return { pathname, hash: '', host: '', hostname: '', href: '', ancestorOrigins: null, assign: () => null, reload: () => null, replace: () => null, origin: '', port: '', protocol: '', search, } } describe('<NavLink />', () => { it('receives active class on the same pathname', () => { const mockLocation = createDummyLocation('/dunder-mifflin') const { getByText } = render( <LocationProvider location={mockLocation}> <NavLink activeClassName="activeTest" to="/dunder-mifflin"> Dunder Mifflin </NavLink> </LocationProvider> ) expect(getByText(/Dunder Mifflin/)).toHaveClass('activeTest') }) it('receives active class on the same pathname with search parameters', () => { const mockLocation = createDummyLocation( '/search-params', '?tab=main&page=1' ) const { getByText } = render( <LocationProvider location={mockLocation}> <NavLink activeClassName="activeTest" to={`/search-params?page=1&tab=main`} > Dunder Mifflin </NavLink> </LocationProvider> ) expect(getByText(/Dunder Mifflin/)).toHaveClass('activeTest') }) it('receives active class on the pathname when we are on a sub page', () => { const mockLocation = createDummyLocation('/users/1') const { getByText } = render( <LocationProvider location={mockLocation}> <NavLink activeClassName="activeTest" matchSubPaths to="/users"> Dunder Mifflin </NavLink> </LocationProvider> ) expect(getByText(/Dunder Mifflin/)).toHaveClass('activeTest') }) it('receives active class on the pathname when we are on the exact page, but also matching child paths', () => { const mockLocation = createDummyLocation('/users/1') const { getByText } = render( <LocationProvider location={mockLocation}> <NavLink activeClassName="activeTest" matchSubPaths to="/users/1"> Dunder Mifflin </NavLink> </LocationProvider> ) expect(getByText(/Dunder Mifflin/)).toHaveClass('activeTest') }) it('receives active class on the same pathname only', () => { const mockLocation = createDummyLocation('/pathname', '?tab=main&page=1') const { getByText } = render( <LocationProvider location={mockLocation}> <NavLink activeClassName="activeTest" to="/pathname?tab=second&page=2" activeMatchParams={[]} > Dunder Mifflin </NavLink> </LocationProvider> ) expect(getByText(/Dunder Mifflin/)).toHaveClass('activeTest') }) it('receives active class on the same pathname with a matched param key', () => { const mockLocation = createDummyLocation( '/pathname-params', '?tab=main&page=1' ) const { getByText } = render( <LocationProvider location={mockLocation}> <NavLink activeClassName="activeTest" to={`/pathname-params?tab=main&page=2`} activeMatchParams={['tab']} > Dunder Mifflin </NavLink> </LocationProvider> ) expect(getByText(/Dunder Mifflin/)).toHaveClass('activeTest') }) it('receives active class on the same pathname with a matched key-value param', () => { const mockLocation = createDummyLocation( '/search-params', '?tab=main&page=1' ) const { getByText } = render( <LocationProvider location={mockLocation}> <NavLink activeClassName="activeTest" to={`/search-params?page=1&tab=main`} activeMatchParams={[{ page: 1 }]} > Dunder Mifflin </NavLink> </LocationProvider> ) expect(getByText(/Dunder Mifflin/)).toHaveClass('activeTest') }) it('receives active class on the same pathname with a matched param key and a matched key-value param', () => { const mockLocation = createDummyLocation( '/search-params', '?tab=main&page=1&category=book' ) const { getByText } = render( <LocationProvider location={mockLocation}> <NavLink activeClassName="activeTest" to={`/search-params?page=3&tab=main&category=book`} activeMatchParams={[{ category: 'book' }, 'page']} > Dunder Mifflin </NavLink> </LocationProvider> ) expect(getByText(/Dunder Mifflin/)).toHaveClass('activeTest') }) it('receives active class on the same pathname with a matched param key and multiple matched key-value param', () => { const mockLocation = createDummyLocation( '/search-params', '?tab=about&page=3&category=magazine' ) const { getByText } = render( <LocationProvider location={mockLocation}> <NavLink activeClassName="activeTest" to={`/search-params?page=3&tab=main&category=magazine`} activeMatchParams={[{ page: 3, category: 'magazine' }, 'tab']} > Dunder Mifflin </NavLink> </LocationProvider> ) expect(getByText(/Dunder Mifflin/)).toHaveClass('activeTest') }) it('receives active class on the same pathname with a matched param key and multiple matched key-value param in separated', () => { const mockLocation = createDummyLocation( '/search-params', '?tab=about&page=3&category=magazine' ) const { getByText } = render( <LocationProvider location={mockLocation}> <NavLink activeClassName="activeTest" to={`/search-params?page=3&tab=main&category=magazine`} activeMatchParams={[{ page: 3 }, { category: 'magazine' }, 'tab']} > Dunder Mifflin </NavLink> </LocationProvider> ) expect(getByText(/Dunder Mifflin/)).toHaveClass('activeTest') }) it('does NOT receive active class on a different path that starts with the same word', () => { const mockLocation = createDummyLocation('/users-settings') const { getByText } = render( <LocationProvider location={mockLocation}> <NavLink activeClassName="activeTest" matchSubPaths to="/users"> Dunder Mifflin </NavLink> </LocationProvider> ) expect(getByText(/Dunder Mifflin/)).not.toHaveClass('activeTest') }) it('does NOT receive active class on different path', () => { const mockLocation = createDummyLocation('/staples') const { getByText } = render( <LocationProvider location={mockLocation}> <NavLink activeClassName="activeTest" to="/dunder-mifflin"> Dunder Mifflin </NavLink> </LocationProvider> ) expect(getByText(/Dunder Mifflin/)).not.toHaveClass('activeTest') }) it('does NOT receive active class on the same pathname with different search params', () => { const mockLocation = createDummyLocation( '/search-params', '?tab=main&page=1' ) const { getByText } = render( <LocationProvider location={mockLocation}> <NavLink activeClassName="activeTest" to={`/search-params?page=2&tab=main`} > Dunder Mifflin </NavLink> </LocationProvider> ) expect(getByText(/Dunder Mifflin/)).not.toHaveClass('activeTest') }) it('does NOT receive active class on the same pathname with a different search param key', () => { const mockLocation = createDummyLocation( '/pathname-params', '?category=car&page=1' ) const { getByText } = render( <LocationProvider location={mockLocation}> <NavLink activeClassName="activeTest" to={`/pathname-params?tab=main&page=2`} activeMatchParams={['tab']} > Dunder Mifflin </NavLink> </LocationProvider> ) expect(getByText(/Dunder Mifflin/)).not.toHaveClass('activeTest') }) }) describe('useMatch', () => { const MyLink = ({ to, ...rest }: React.ComponentPropsWithoutRef<typeof Link>) => { const [pathname, queryString] = to.split('?') const matchInfo = useMatch(pathname, { searchParams: flattenSearchParams(queryString), }) return ( <Link to={to} style={{ color: matchInfo.match ? 'green' : 'red' }} {...rest} /> ) } it('returns a match on the same pathname', () => { const mockLocation = createDummyLocation('/dunder-mifflin') const { getByText } = render( <LocationProvider location={mockLocation}> <MyLink to="/dunder-mifflin">Dunder Mifflin</MyLink> </LocationProvider> ) expect(getByText(/Dunder Mifflin/)).toHaveStyle('color: green') }) it('returns a match on the same pathname with search parameters', () => { const mockLocation = createDummyLocation( '/search-params', '?page=1&tab=main' ) const { getByText } = render( <LocationProvider location={mockLocation}> <MyLink to={`/search-params?tab=main&page=1`}>Dunder Mifflin</MyLink> </LocationProvider> ) expect(getByText(/Dunder Mifflin/)).toHaveStyle('color: green') }) it('does NOT receive active class on different path', () => { const mockLocation = createDummyLocation('/staples') const { getByText } = render( <LocationProvider location={mockLocation}> <MyLink to="/dunder-mifflin">Dunder Mifflin</MyLink> </LocationProvider> ) expect(getByText(/Dunder Mifflin/)).toHaveStyle('color: red') }) it('does NOT receive active class on the same pathname with different parameters', () => { const mockLocation = createDummyLocation( '/search-params', '?tab=main&page=1' ) const { getByText } = render( <LocationProvider location={mockLocation}> <MyLink to={`/search-params?page=2&tab=main`}>Dunder Mifflin</MyLink> </LocationProvider> ) expect(getByText(/Dunder Mifflin/)).toHaveStyle('color: red') }) })
5,808
0
petrpan-code/redwoodjs/redwood/packages/router/src
petrpan-code/redwoodjs/redwood/packages/router/src/__tests__/location.test.tsx
import { render } from '@testing-library/react' import '@testing-library/jest-dom/extend-expect' import { LocationProvider, useLocation } from '../location' describe('useLocation', () => { const TestComponent = () => { const location = useLocation() return ( <div> <p>{JSON.stringify(location)}</p> <input data-testid="pathname" defaultValue={location.pathname} /> <input data-testid="search" defaultValue={location.search} /> <input data-testid="hash" defaultValue={location.hash} /> </div> ) } it('returns the correct pathname, search, and hash values', () => { const mockLocation = { pathname: '/dunder-mifflin', search: '?facts=bears', hash: '#woof', } const { getByText, getByTestId } = render( <LocationProvider location={mockLocation}> <TestComponent /> </LocationProvider> ) expect( getByText( '{"pathname":"/dunder-mifflin","search":"?facts=bears","hash":"#woof"}' ) ).toBeInTheDocument() expect(getByTestId('pathname')).toHaveValue('/dunder-mifflin') expect(getByTestId('search')).toHaveValue('?facts=bears') expect(getByTestId('hash')).toHaveValue('#woof') }) })
5,809
0
petrpan-code/redwoodjs/redwood/packages/router/src
petrpan-code/redwoodjs/redwood/packages/router/src/__tests__/nestedSets.test.tsx
import * as React from 'react' import type { ReactNode } from 'react' import '@testing-library/jest-dom/extend-expect' import { act, render } from '@testing-library/react' import { navigate, Route, Router } from '../' import { Private, Set } from '../Set' // Heads-up, in this test we're not mocking LazyComponent because all the tests // explicitly define the pages in the router. // // If you add tests with dynamic imports, i.e. all the pages aren't explicitly // supplied to the router, then you'll need to mock LazyComponent (see // router.test.tsx) const HomePage = () => <h1>Home Page</h1> const Page = () => <h1>Page</h1> interface LayoutProps { children: ReactNode } beforeEach(() => { window.history.pushState({}, '', '/') }) let err: typeof console.error beforeAll(() => { // Hide thrown exceptions. We're expecting them, and they clutter the output err = console.error console.error = jest.fn() }) afterAll(() => { console.error = err }) test('Sets nested in Private should not error out if no authenticated prop provided', () => { const Layout1 = ({ children }: LayoutProps) => ( <div> <p>Layout1</p> {children} </div> ) const SetInsidePrivate = () => ( <Router> <Route path="/" page={HomePage} name="home" /> <Route path="/auth" page={() => 'Regular Auth'} name="auth" /> <Route path="/adminAuth" page={() => 'Admin Auth'} name="adminAuth" /> <Private unauthenticated="auth"> <Route path="/two/{slug}" page={Page} name="two" /> {/* The Set below is private implicitly (nested under private), but should not need an unauthenticated prop */} <Set wrap={Layout1}> <Private roles="admin" unauthenticated="adminAuth"> <Route path="/three" page={Page} name="three" /> </Private> </Set> </Private> <Set wrap={Layout1} private> <Route path="/four" page={Page} name="four" /> </Set> </Router> ) render(<SetInsidePrivate />) expect(() => { act(() => navigate('/three')) }).not.toThrowError() // But still throws if you try to navigate to a private route without an unauthenticated prop expect(() => { act(() => navigate('/four')) }).toThrowError('You must specify an `unauthenticated` route') }) test('Sets nested in `<Set private>` should not error out if no authenticated prop provided', () => { const Layout1 = ({ children }: { children: ReactNode }) => ( <div> <p>Layout1</p> {children} </div> ) const SetInsideSetPrivate = () => ( <Router> <Route path="/" page={HomePage} name="home" /> <Route path="/auth" page={() => 'Regular Auth'} name="auth" /> <Route path="/adminAuth" page={() => 'Admin Auth'} name="adminAuth" /> <Set private unauthenticated="auth"> <Route path="/two/{slug}" page={Page} name="two" /> {/* The Set below is private implicitly (nested under private), but should not need an unauthenticated prop */} <Set wrap={Layout1}> <Private roles="admin" unauthenticated="adminAuth"> <Route path="/three" page={Page} name="three" /> </Private> </Set> </Set> <Set wrap={Layout1} private> <Route path="/four" page={Page} name="four" /> </Set> </Router> ) render(<SetInsideSetPrivate />) expect(() => act(() => navigate('/three'))).not.toThrowError() // But still throws if you try to navigate to a private route without an unauthenticated prop expect(() => act(() => navigate('/four'))).toThrowError( 'You must specify an `unauthenticated` route' ) }) test('Nested sets should not cause a re-mount of parent wrap components', async () => { const layoutOneMount = jest.fn() const layoutOneUnmount = jest.fn() const layoutTwoMount = jest.fn() const layoutTwoUnmount = jest.fn() const Layout1 = ({ children }: LayoutProps) => { React.useEffect(() => { // Called on mount and re-mount of this layout layoutOneMount() return () => { layoutOneUnmount() } }, []) return ( <> <p>ONE</p> {children} </> ) } const Layout2 = ({ children }: LayoutProps) => { React.useEffect(() => { // Called on mount and re-mount of this layout layoutTwoMount() return () => { layoutTwoUnmount() } }, []) return ( <> <p>TWO</p> {children} </> ) } const NestedSetsWithWrap = () => ( <Router> <Set wrap={Layout1}> <Route path="/" page={HomePage} name="home" /> <Set wrap={Layout2}> <Route path="/posts/new" page={Page} name="newPost" /> <Route path="/posts/{id:Int}/edit" page={Page} name="editPost" /> <Route path="/posts/{id:Int}" page={Page} name="post" /> <Route path="/posts" page={Page} name="posts" /> </Set> </Set> </Router> ) render(<NestedSetsWithWrap />) // Layout 1 is mounted on initial render because we start out on / // Layout 2 is not mounted at all expect(layoutOneMount).toHaveBeenCalledTimes(1) expect(layoutOneUnmount).toHaveBeenCalledTimes(0) expect(layoutTwoMount).toHaveBeenCalledTimes(0) expect(layoutTwoUnmount).toHaveBeenCalledTimes(0) act(() => navigate('/')) // Haven't navigated anywhere, so nothing should have changed expect(layoutOneMount).toHaveBeenCalledTimes(1) expect(layoutOneUnmount).toHaveBeenCalledTimes(0) expect(layoutTwoMount).toHaveBeenCalledTimes(0) expect(layoutTwoUnmount).toHaveBeenCalledTimes(0) act(() => navigate('/posts')) // Layout 2 should now have been mounted // We're still within Layout 1, so it should not have been unmounted expect(layoutOneMount).toHaveBeenCalledTimes(1) expect(layoutOneUnmount).toHaveBeenCalledTimes(0) expect(layoutTwoMount).toHaveBeenCalledTimes(1) expect(layoutTwoUnmount).toHaveBeenCalledTimes(0) act(() => navigate('/')) // Navigating back up to / should unmount Layout 2 but crucially not remount // Layout 1 expect(layoutOneMount).toHaveBeenCalledTimes(1) expect(layoutOneUnmount).toHaveBeenCalledTimes(0) expect(layoutTwoMount).toHaveBeenCalledTimes(1) expect(layoutTwoUnmount).toHaveBeenCalledTimes(1) act(() => navigate('/posts')) // Going back to /posts should remount Layout 2 but not Layout 1 expect(layoutOneMount).toHaveBeenCalledTimes(1) expect(layoutOneUnmount).toHaveBeenCalledTimes(0) expect(layoutTwoMount).toHaveBeenCalledTimes(2) expect(layoutTwoUnmount).toHaveBeenCalledTimes(1) act(() => navigate('/posts')) // Navigating within Layout 2 should not remount any of the layouts expect(layoutOneMount).toHaveBeenCalledTimes(1) expect(layoutOneUnmount).toHaveBeenCalledTimes(0) expect(layoutTwoMount).toHaveBeenCalledTimes(2) expect(layoutTwoUnmount).toHaveBeenCalledTimes(1) act(() => navigate('/')) // Back up to / again and we should see Layout 2 unmount expect(layoutOneMount).toHaveBeenCalledTimes(1) expect(layoutOneUnmount).toHaveBeenCalledTimes(0) expect(layoutTwoMount).toHaveBeenCalledTimes(2) expect(layoutTwoUnmount).toHaveBeenCalledTimes(2) })
5,810
0
petrpan-code/redwoodjs/redwood/packages/router/src
petrpan-code/redwoodjs/redwood/packages/router/src/__tests__/redirect.test.tsx
import React from 'react' import { act, render, waitFor } from '@testing-library/react' import { navigate } from '../history' import { Route, Router } from '../router' const RedirectedRoutes = () => ( <Router> <Route path="/simple" redirect="/redirectedSimple" name="simple" /> <Route path="/redirectedSimple" name="redirectedSimple" page={() => <h1>FINDME</h1>} /> </Router> ) test('Redirected route', async () => { const screen = render(<RedirectedRoutes />) act(() => navigate('/simple')) await waitFor(() => screen.getByText('FINDME')) })
5,811
0
petrpan-code/redwoodjs/redwood/packages/router/src
petrpan-code/redwoodjs/redwood/packages/router/src/__tests__/route-announcer.test.tsx
import React from 'react' import { render, waitFor, act } from '@testing-library/react' import '@testing-library/jest-dom/extend-expect' import { getAnnouncement } from '../a11yUtils' import { navigate } from '../history' import RouteAnnouncement from '../route-announcement' import { Router, Route, routes } from '../router' // SETUP const HomePage = () => <h1>Home Page</h1> const RouteAnnouncementPage = () => ( <> <h1>RouteAnnouncement Page </h1> <RouteAnnouncement visuallyHidden> RouteAnnouncement content </RouteAnnouncement> <main>main content</main> </> ) const H1Page = () => ( <> <h1>H1 Page</h1> <main>main content</main> </> ) const NoH1Page = () => ( <> <div>NoH1 Page</div> <main>main content</main> </> ) const NoH1OrTitlePage = () => ( <> <div>NoH1OrTitle Page</div> <main>main content</main> </> ) const EmptyH1Page = () => ( <> <h1></h1> <main>Empty H1 Page</main> </> ) beforeEach(() => { window.history.pushState({}, '', '/') // @ts-expect-error - No type gen here for routes like there is in a real app Object.keys(routes).forEach((key) => delete routes[key]) }) test('route announcer renders with aria-live="assertive" and role="alert"', async () => { const TestRouter = () => ( <Router> <Route path="/" page={HomePage} name="home" /> </Router> ) const screen = render(<TestRouter />) await waitFor(() => { screen.getByText(/Home Page/i) const routeAnnouncer = screen.getByRole('alert') const ariaLiveValue = routeAnnouncer.getAttribute('aria-live') const roleValue = routeAnnouncer.getAttribute('role') expect(ariaLiveValue).toBe('assertive') expect(roleValue).toBe('alert') }) }) test('gets the announcement in the correct order of priority', async () => { const TestRouter = () => ( <Router> <Route path="/" page={RouteAnnouncementPage} name="routeAnnouncement" /> <Route path="/h1" page={H1Page} name="h1" /> <Route path="/noH1" page={NoH1Page} name="noH1" /> <Route path="/noH1OrTitle" page={NoH1OrTitlePage} name="noH1OrTitle" /> </Router> ) const screen = render(<TestRouter />) // starts on route announcement. // since there's a RouteAnnouncement, it should announce that. await waitFor(() => { screen.getByText(/RouteAnnouncement Page/i) expect(getAnnouncement()).toBe('RouteAnnouncement content') }) // navigate to h1 // since there's no RouteAnnouncement, it should announce the h1. // @ts-expect-error - No type gen here for routes like there is in a real app act(() => navigate(routes.h1())) await waitFor(() => { screen.getByText(/H1 Page/i) expect(getAnnouncement()).toBe('H1 Page') }) // navigate to noH1. // since there's no h1, it should announce the title. // @ts-expect-error - No type gen here for routes like there is in a real app act(() => navigate(routes.noH1())) await waitFor(() => { screen.getByText(/NoH1 Page/i) document.title = 'title content' expect(getAnnouncement()).toBe('title content') document.title = '' }) // navigate to noH1OrTitle. // since there's no h1 or title, // it should announce the location. // @ts-expect-error - No type gen here for routes like there is in a real app act(() => navigate(routes.noH1OrTitle())) await waitFor(() => { screen.getByText(/NoH1OrTitle Page/i) expect(getAnnouncement()).toBe('new page at /noH1OrTitle') }) }) test('getAnnouncement handles empty PageHeader', async () => { const TestRouter = () => ( <Router> <Route path="/" page={EmptyH1Page} name="emptyH1" /> </Router> ) const screen = render(<TestRouter />) await waitFor(() => { screen.getByText(/Empty H1 Page/i) document.title = 'title content' expect(getAnnouncement()).toBe('title content') document.title = '' }) })
5,812
0
petrpan-code/redwoodjs/redwood/packages/router/src
petrpan-code/redwoodjs/redwood/packages/router/src/__tests__/route-focus.test.tsx
import { render, waitFor } from '@testing-library/react' import '@testing-library/jest-dom/extend-expect' import { getFocus } from '../a11yUtils' import RouteFocus from '../route-focus' import { Router, Route, routes } from '../router' // SETUP const RouteFocusPage = () => ( <> <RouteFocus> <a>a link is a focusable element</a> </RouteFocus> <h1>Route Focus Page</h1> <p></p> </> ) const NoRouteFocusPage = () => <h1>No Route Focus Page</h1> const RouteFocusNoChildren = () => ( <> {/* @ts-expect-error - Testing a JS scenario */} <RouteFocus></RouteFocus> <h1>Route Focus No Children Page</h1> <p></p> </> ) const RouteFocusTextNodePage = () => ( <> <RouteFocus>some text</RouteFocus> <h1>Route Focus Text Node Page </h1> <p></p> </> ) const RouteFocusNegativeTabIndexPage = () => ( <> <RouteFocus> <p>my tabindex is -1</p> </RouteFocus> <h1>Route Focus Negative Tab Index Page </h1> <p></p> </> ) beforeEach(() => { window.history.pushState({}, '', '/') // @ts-expect-error - No type gen here for routes like there is in a real app Object.keys(routes).forEach((key) => delete routes[key]) }) test('getFocus returns a focusable element if RouteFocus has one', async () => { const TestRouter = () => ( <Router> <Route path="/" page={RouteFocusPage} name="routeFocus" /> </Router> ) const screen = render(<TestRouter />) await waitFor(() => { screen.getByText(/Route Focus Page/i) const routeFocus = getFocus() expect(routeFocus).toHaveTextContent('a link is a focusable element') }) }) test("getFocus returns null if there's no RouteFocus", async () => { const TestRouter = () => ( <Router> <Route path="/" page={NoRouteFocusPage} name="noRouteFocus" /> </Router> ) const screen = render(<TestRouter />) await waitFor(() => { screen.getByText(/No Route Focus Page/i) const routeFocus = getFocus() expect(routeFocus).toBeNull() }) }) test("getFocus returns null if RouteFocus doesn't have any children", async () => { const TestRouter = () => ( <Router> <Route path="/" page={RouteFocusNoChildren} name="routeFocusNoChildren" /> </Router> ) const screen = render(<TestRouter />) await waitFor(() => { screen.getByText(/Route Focus No Children Page/i) const routeFocus = getFocus() expect(routeFocus).toBeNull() }) }) test('getFocus returns null if RouteFocus has just a Text node', async () => { const TestRouter = () => ( <Router> <Route path="/" page={RouteFocusTextNodePage} name="routeFocusTextNode" /> </Router> ) const screen = render(<TestRouter />) await waitFor(() => { screen.getByText(/Route Focus Text Node Page/i) const routeFocus = getFocus() expect(routeFocus).toBeNull() }) }) test("getFocus returns null if RouteFocus's child isn't focusable", async () => { const TestRouter = () => ( <Router> <Route path="/" page={RouteFocusNegativeTabIndexPage} name="routeFocusNegativeTabIndex" /> </Router> ) const screen = render(<TestRouter />) await waitFor(() => { screen.getByText(/Route Focus Negative Tab Index Page/i) const routeFocus = getFocus() expect(routeFocus).toBeNull() }) })
5,813
0
petrpan-code/redwoodjs/redwood/packages/router/src
petrpan-code/redwoodjs/redwood/packages/router/src/__tests__/route-validators.test.tsx
import { isValidRoute } from '../route-validators' import { Route } from '../router' describe('isValidRoute', () => { it('throws if Route does not have a path', () => { // @ts-expect-error Its ok mate, we're checking the validator const RouteCheck = <Route name="noPath" page={() => <h1>Hello</h1>} /> expect(() => isValidRoute(RouteCheck)).toThrowError( 'Route element for "noPath" is missing required props: path' ) }) it('throws if a standard Route does not have a name', () => { // @ts-expect-error Its ok mate, we're checking the validator const RouteCheck = <Route path="/hello" page={() => <h1>Hello</h1>} /> expect(() => isValidRoute(RouteCheck)).toThrowError( 'Route element for "/hello" is missing required props: name' ) }) it('throws if Route does not have a page or path', () => { // @ts-expect-error Its ok mate, we're checking the validator const RouteCheck = <Route name="noPage" /> expect(() => isValidRoute(RouteCheck)).toThrowError( 'Route element for "noPage" is missing required props: path, page' ) }) it('throws if redirect Route does have have a path', () => { // @ts-expect-error Its ok mate, we're checking the validator const RouteToCheck = <Route redirect="/dash" /> expect(() => isValidRoute(RouteToCheck)).toThrowError( 'Route element is missing required props: path' ) }) it('throws if notFoundPage doesnt have page prop', () => { // @ts-expect-error Its ok mate, we're checking the validator const RouteToCheck = <Route notfound name="bazinga" /> expect(() => isValidRoute(RouteToCheck)).toThrowError( 'Route element for "bazinga" is missing required props: page' ) }) it('does not throws if notFoundPage doesnt have a path', () => { // @ts-expect-error Its ok mate, we're checking the validator const RouteToCheck = <Route name="bazinga" notfound page={() => <></>} /> expect(() => isValidRoute(RouteToCheck)).not.toThrow() }) })
5,814
0
petrpan-code/redwoodjs/redwood/packages/router/src
petrpan-code/redwoodjs/redwood/packages/router/src/__tests__/routeScrollReset.test.tsx
import React from 'react' import '@testing-library/jest-dom/extend-expect' import { act, cleanup, render, screen } from '@testing-library/react' import { navigate } from '../history' import { Route, Router, routes } from '../router' describe('Router scroll reset', () => { const Page1 = () => <div>Page 1</div> const Page2 = () => <div>Page 2</div> const TestRouter = () => ( <Router> <Route path="/" page={Page1} name="page1" /> <Route path="/two" page={Page2} name="page2" /> </Router> ) // Redfine the mocks here again (already done in jest.setup) // Otherwise the mock doesn't clear for some reason globalThis.scrollTo = jest.fn() beforeEach(async () => { ;(globalThis.scrollTo as jest.Mock).mockClear() render(<TestRouter />) // Make sure we're starting on the home route await screen.getByText('Page 1') }) afterEach(async () => { // @NOTE: for some reason, the Router state does not reset between renders act(() => navigate('/')) cleanup() }) it('resets on location/path change', async () => { act(() => navigate( // @ts-expect-error - AvailableRoutes built in project only routes.page2() ) ) await screen.getByText('Page 2') expect(globalThis.scrollTo).toHaveBeenCalledTimes(1) }) it('resets on location/path and queryChange change', async () => { act(() => navigate( // @ts-expect-error - AvailableRoutes built in project only routes.page2({ tab: 'three', }) ) ) await screen.getByText('Page 2') expect(globalThis.scrollTo).toHaveBeenCalledTimes(1) }) it('resets scroll on query params (search) change on the same page', async () => { act(() => // We're staying on page 1, but changing the query params navigate( // @ts-expect-error - AvailableRoutes built in project only routes.page1({ queryParam1: 'foo', }) ) ) await screen.getByText('Page 1') expect(globalThis.scrollTo).toHaveBeenCalledTimes(1) }) it('does NOT reset on hash change', async () => { await screen.getByText('Page 1') act(() => // Stay on page 1, but change the hash navigate(`#route=66`, { replace: true }) ) await screen.getByText('Page 1') expect(globalThis.scrollTo).not.toHaveBeenCalled() }) })
5,815
0
petrpan-code/redwoodjs/redwood/packages/router/src
petrpan-code/redwoodjs/redwood/packages/router/src/__tests__/router.test.tsx
let mockDelay = 0 jest.mock('../util', () => { const actualUtil = jest.requireActual('../util') const { lazy } = jest.requireActual('react') return { ...actualUtil, normalizePage: (specOrPage: Spec | React.ComponentType<unknown>) => ({ name: specOrPage.name, prerenderLoader: () => ({ default: specOrPage }), LazyComponent: lazy( () => new Promise((resolve) => setTimeout(() => resolve({ default: specOrPage }), mockDelay) ) ), }), } }) import React, { useEffect, useState } from 'react' import '@testing-library/jest-dom/extend-expect' import { act, configure, fireEvent, render, waitFor, } from '@testing-library/react' import type { AuthContextInterface, UseAuth } from '@redwoodjs/auth' import { back, routes as generatedRoutes, Link, navigate, Private, PrivateSet, Redirect, Route, Router, usePageLoadingContext, } from '../' import { useLocation } from '../location' import { useParams } from '../params' import { Set } from '../Set' import type { GeneratedRoutesMap, Spec } from '../util' /** running into intermittent test timeout behavior in https://github.com/redwoodjs/redwood/pull/4992 attempting to work around by bumping the default timeout of 5000 */ const timeoutForFlakeyAsyncTests = 8000 type UnknownAuthContextInterface = AuthContextInterface< unknown, unknown, unknown, unknown, unknown, unknown, unknown, unknown, unknown, unknown, unknown, unknown > // The types are generated in the user's project const routes = generatedRoutes as GeneratedRoutesMap function createDummyAuthContextValues( partial: Partial<UnknownAuthContextInterface> ) { const authContextValues: UnknownAuthContextInterface = { loading: true, isAuthenticated: false, userMetadata: null, currentUser: null, logIn: async () => null, logOut: async () => null, signUp: async () => null, getToken: async () => null, getCurrentUser: async () => null, hasRole: () => false, reauthenticate: async () => {}, client: null, type: 'custom', hasError: false, forgotPassword: async () => null, resetPassword: async () => null, validateResetToken: async () => null, } return { ...authContextValues, ...partial } } interface MockAuth { isAuthenticated?: boolean loading?: boolean hasRole?: boolean | ((role: string[]) => boolean) loadingTimeMs?: number } const mockUseAuth = ( { isAuthenticated = false, loading = false, hasRole = false, loadingTimeMs, }: MockAuth = { isAuthenticated: false, loading: false, hasRole: false, } ) => () => { const [authLoading, setAuthLoading] = useState(loading) const [authIsAuthenticated, setAuthIsAuthenticated] = useState(isAuthenticated) useEffect(() => { let timer: NodeJS.Timeout | undefined if (loadingTimeMs) { timer = setTimeout(() => { setAuthLoading(false) setAuthIsAuthenticated(true) }, loadingTimeMs) } return () => { if (timer) { clearTimeout(timer) } } }, []) return createDummyAuthContextValues({ loading: authLoading, isAuthenticated: authIsAuthenticated, hasRole: typeof hasRole === 'boolean' ? () => hasRole : hasRole, }) } interface LayoutProps { children: React.ReactNode } const HomePage = () => <h1>Home Page</h1> const LoginPage = () => <h1>Login Page</h1> const AboutPage = () => <h1>About Page</h1> const PrivatePage = () => <h1>Private Page</h1> const RedirectPage = () => <Redirect to="/about" /> const NotFoundPage = () => <h1>404</h1> const ParamPage = ({ value, q }: { value: string; q: string }) => { const params = useParams() return ( <div> <p>param {`${value}${q}`}</p> <p>hookparams {`${params.value}?${params.q}`}</p> </div> ) } configure({ asyncUtilTimeout: 5_000, }) beforeEach(() => { window.history.pushState({}, '', '/') Object.keys(routes).forEach((key) => delete routes[key]) }) describe('slow imports', () => { const HomePagePlaceholder = () => <>HomePagePlaceholder</> const AboutPagePlaceholder = () => <>AboutPagePlaceholder</> const ParamPagePlaceholder = () => <>ParamPagePlaceholder</> const RedirectPagePlaceholder = () => <>RedirectPagePlaceholder</> const PrivatePagePlaceholder = () => <>PrivatePagePlaceholder</> const LoginPagePlaceholder = () => <>LoginPagePlaceholder</> const LocationPage = () => { const location = useLocation() return ( <> <h1>Location Page</h1> <p>{location.pathname}</p> </> ) } const PageLoadingContextLayout = ({ children }: LayoutProps) => { const { loading } = usePageLoadingContext() return ( <> <h1>Page Loading Context Layout</h1> {loading && <p>loading in layout...</p>} {!loading && <p>done loading in layout</p>} {children} </> ) } const PageLoadingContextPage = () => { const { loading } = usePageLoadingContext() return ( <> <h1>Page Loading Context Page</h1> {loading && <p>loading in page...</p>} {!loading && <p>done loading in page</p>} </> ) } const TestRouter = ({ authenticated, hasRole, }: { authenticated?: boolean hasRole?: boolean }) => ( <Router useAuth={mockUseAuth({ isAuthenticated: authenticated, hasRole })} pageLoadingDelay={0} > <Route path="/" page={HomePage} name="home" whileLoadingPage={HomePagePlaceholder} /> <Route path="/about" page={AboutPage} name="about" whileLoadingPage={AboutPagePlaceholder} /> <Route path="/redirect" page={RedirectPage} name="redirect" whileLoadingPage={RedirectPagePlaceholder} /> <Route path="/redirect2/{value}" redirect="/param-test/{value}" /> <Route path="/login" page={LoginPage} name="login" whileLoadingPage={LoginPagePlaceholder} /> <PrivateSet unauthenticated="login"> <Route path="/private" page={PrivatePage} name="private" whileLoadingPage={PrivatePagePlaceholder} /> </PrivateSet> <PrivateSet unauthenticated="login" roles="admin"> <Route path="/private_with_role" page={PrivatePage} name="private_with_role" whileLoadingPage={PrivatePagePlaceholder} /> </PrivateSet> {/* Keeping this one around for now, so we don't accidentally break Private until we're ready to remove it */} <Private unauthenticated="login" roles={['admin', 'moderator']}> <Route path="/private_with_several_roles" page={PrivatePage} name="private_with_several_roles" whileLoadingPage={PrivatePagePlaceholder} /> </Private> <Route path="/param-test/{value}" page={ParamPage} name="params" whileLoadingPage={ParamPagePlaceholder} /> <Route path="/location" page={LocationPage} name="home" /> <Set wrap={PageLoadingContextLayout}> <Route path="/page-loading-context" page={PageLoadingContextPage} name="pageLoadingContext" /> </Set> <Route notfound page={NotFoundPage} /> </Router> ) beforeEach(() => { // One of the tests modifies this, so we need to reset it before each test mockDelay = 400 }) afterEach(() => { mockDelay = 0 }) test( 'Basic home page', async () => { const screen = render(<TestRouter />) await waitFor(() => screen.getByText('HomePagePlaceholder')) await waitFor(() => screen.getByText('Home Page')) }, timeoutForFlakeyAsyncTests ) test( 'Navigation', async () => { const screen = render(<TestRouter />) // First we should render an empty page while waiting for pageLoadDelay to // pass //TODO: implement pageLoadDelay potentially don't need with preloading features // expect(screen.container).toBeEmptyDOMElement() // Then we should render whileLoadingPage await waitFor(() => screen.getByText('HomePagePlaceholder')) // Finally we should render the actual page await waitFor(() => screen.getByText('Home Page')) act(() => navigate('/about')) // Now after navigating we should keep rendering the previous page until // the new page has loaded, or until pageLoadDelay has passed. This // ensures we don't show a "white flash", i.e. render an empty page, while // navigating the page expect(screen.container).not.toBeEmptyDOMElement() await waitFor(() => screen.getByText('Home Page')) expect(screen.container).not.toBeEmptyDOMElement() // As for HomePage we first render the placeholder... await waitFor(() => screen.getByText('AboutPagePlaceholder')) // ...and then the actual page await waitFor(() => screen.getByText('About Page')) }, timeoutForFlakeyAsyncTests ) test( 'Redirect page', async () => { act(() => navigate('/redirect')) const screen = render(<TestRouter />) await waitFor(() => screen.getByText('RedirectPagePlaceholder')) await waitFor(() => screen.getByText('About Page')) }, timeoutForFlakeyAsyncTests ) test( 'Redirect route', async () => { const screen = render(<TestRouter />) await waitFor(() => screen.getByText('HomePagePlaceholder')) await waitFor(() => screen.getByText('Home Page')) act(() => navigate('/redirect2/redirected?q=cue')) await waitFor(() => screen.getByText('ParamPagePlaceholder')) await waitFor(() => screen.getByText('param redirectedcue')) }, timeoutForFlakeyAsyncTests ) test( 'Private page when not authenticated', async () => { act(() => navigate('/private')) const screen = render(<TestRouter />) await waitFor(() => { expect( screen.queryByText('PrivatePagePlaceholder') ).not.toBeInTheDocument() expect(screen.queryByText('Private Page')).not.toBeInTheDocument() expect(screen.queryByText('LoginPagePlaceholder')).toBeInTheDocument() }) await waitFor(() => screen.getByText('Login Page')) }, timeoutForFlakeyAsyncTests ) test( 'Private page when authenticated', async () => { act(() => navigate('/private')) const screen = render(<TestRouter authenticated={true} />) await waitFor(() => screen.getByText('PrivatePagePlaceholder')) await waitFor(() => screen.getByText('Private Page')) await waitFor(() => { expect(screen.queryByText('Login Page')).not.toBeInTheDocument() }) }, timeoutForFlakeyAsyncTests ) test( 'Private page when authenticated but does not have the role', async () => { act(() => navigate('/private_with_role')) const screen = render(<TestRouter authenticated={true} hasRole={false} />) await waitFor(() => { expect( screen.queryByText('PrivatePagePlaceholder') ).not.toBeInTheDocument() expect(screen.queryByText('Private Page')).not.toBeInTheDocument() expect(screen.queryByText('LoginPagePlaceholder')).toBeInTheDocument() }) await waitFor(() => screen.getByText('Login Page')) }, timeoutForFlakeyAsyncTests ) test( 'Private page when authenticated but does have the role', async () => { act(() => navigate('/private_with_role')) const screen = render(<TestRouter authenticated={true} hasRole={true} />) await waitFor(() => { expect( screen.queryByText('PrivatePagePlaceholder') ).not.toBeInTheDocument() expect(screen.queryByText('Private Page')).toBeInTheDocument() }) }, timeoutForFlakeyAsyncTests ) test( 'useLocation', async () => { act(() => navigate('/location')) const screen = render(<TestRouter />) await waitFor(() => screen.getByText('Location Page')) await waitFor(() => screen.getByText('/location')) act(() => navigate('/about')) // After navigating we will keep rendering the previous page for 100 ms, // (which is our configured delay) before rendering the "whileLoading" // page. // TODO: We don't currently implement page loading delay anymore // await waitFor(() => screen.getByText('Location Page')) // And then we'll render the placeholder... await waitFor(() => screen.getByText('AboutPagePlaceholder')) // ...followed by the actual page await waitFor(() => screen.getByText('About Page')) }, timeoutForFlakeyAsyncTests ) test( 'path params should never be empty', async () => { const PathParamPage = ({ value }: { value: string }) => { expect(value).not.toBeFalsy() return <p>{value}</p> } const TestRouter = () => ( <Router pageLoadingDelay={100}> <Route path="/about" page={AboutPage} name="about" whileLoadingPage={AboutPagePlaceholder} /> <Route path="/path-param-test/{value}" page={PathParamPage} name="params" whileLoadingPage={ParamPagePlaceholder} /> </Router> ) act(() => navigate('/path-param-test/test_value')) const screen = render(<TestRouter />) // First we render the path parameter value "test_value" await waitFor(() => screen.getByText('test_value')) act(() => navigate('/about')) // After navigating we should keep displaying the old path value... await waitFor(() => screen.getByText('test_value')) // ...until we switch over to render the about page loading component... await waitFor(() => screen.getByText('AboutPagePlaceholder')) // ...followed by the actual page await waitFor(() => screen.getByText('About Page')) }, timeoutForFlakeyAsyncTests ) test( 'usePageLoadingContext', async () => { // We want to show a loading indicator if loading pages is taking a long // time. But at the same time we don't want to show it right away, because // then there'll be a flash of the loading indicator on every page load. // So we have a `pageLoadingDelay` delay to control how long it waits // before showing the loading state (default is 1000 ms). // // RW lazy loads pages by default, that's why it could potentially take a // while to load a page. But during tests we don't do that. So we have to // fake a delay. That's what `mockDelay` is for. `mockDelay` has to be // longer than `pageLoadingDelay`, but not too long so the test takes // longer than it has to, and also not too long so the entire test times // out. // Had to increase this to make the test pass on Windows mockDelay = 700 // <TestRouter> sets pageLoadingDelay={200}. (Default is 1000.) const screen = render(<TestRouter />) act(() => navigate('/page-loading-context')) // 'Page Loading Context Layout' should always be shown await waitFor(() => screen.getByText('Page Loading Context Layout')) // 'loading in layout...' should only be shown while the page is loading. // So in this case, for the first 700ms await waitFor(() => screen.getByText('loading in layout...')) // After 700ms 'Page Loading Context Page' should be rendered await waitFor(() => screen.getByText('Page Loading Context Page')) // This shouldn't show up, because the page shouldn't render before it's // fully loaded expect(screen.queryByText('loading in page...')).not.toBeInTheDocument() await waitFor(() => screen.getByText('done loading in page')) await waitFor(() => screen.getByText('done loading in layout')) }, timeoutForFlakeyAsyncTests ) }) describe('inits routes and navigates as expected', () => { const TestRouter = () => ( <Router> <Route path="/" page={HomePage} name="home" /> <Route path="/about" page={AboutPage} name="about" /> <Route path="/redirect" page={RedirectPage} name="redirect" /> <Route path="/redirect2/{value}" redirect="/param-test/{value}" /> <PrivateSet unauthenticated="home"> <Route path="/private" page={PrivatePage} name="private" /> </PrivateSet> <Route path="/param-test/{value}" page={ParamPage} name="params" /> <Route notfound page={NotFoundPage} /> </Router> ) const getScreen = () => render(<TestRouter />) test('starts on home page', async () => { const screen = getScreen() await waitFor(() => screen.getByText(/Home Page/i)) }) test('navigate to about page', async () => { const screen = getScreen() act(() => navigate(routes.about())) await waitFor(() => screen.getByText(/About Page/i)) }) test('passes search params to the page', async () => { const screen = getScreen() act(() => navigate(routes.params({ value: 'val', q: 'q' }))) await waitFor(() => { expect(screen.queryByText('param valq')).toBeInTheDocument() expect(screen.queryByText('hookparams val?q')).toBeInTheDocument() }) }) test('navigate to redirect page should redirect to about', async () => { const screen = getScreen() act(() => navigate(routes.redirect())) await waitFor(() => { expect(screen.queryByText(/Redirect Page/)).not.toBeInTheDocument() expect(screen.queryByText(/About Page/)).toBeInTheDocument() }) }) test('navigate to redirect2 should forward params', async () => { const screen = getScreen() await waitFor(() => screen.getByText(/Home Page/i)) act(() => navigate('/redirect2/redirected?q=cue')) await waitFor(() => screen.getByText(/param redirectedcue/i)) act(() => navigate('/redirect2/redirected')) await waitFor(() => screen.getByText(/param redirected/)) }) test('multiple navigates to params page should update params', async () => { const screen = getScreen() act(() => navigate(routes.params({ value: 'one' }))) await waitFor(() => screen.getByText(/param one/i)) act(() => navigate(routes.params({ value: 'two' }))) await waitFor(() => screen.getByText(/param two/i)) }) test('notfound page catches undefined paths', async () => { const screen = getScreen() act(() => navigate('/no/route/defined')) await waitFor(() => screen.getByText('404')) }) }) describe('test params escaping', () => { const ParamPage = ({ value, q }: { value: string; q: string }) => { const params = useParams() return ( <div> <p>param {`${value}${q}`}</p> <p>hookparams {`${params.value}?${params.q}`}</p> </div> ) } const TestRouter = () => ( <Router> <Route path="/redirect2/{value}" redirect="/param-test/{value}" /> <Route path="/param-test/{value}" page={ParamPage} name="params" /> <Route notfound page={NotFoundPage} /> </Router> ) const getScreen = () => render(<TestRouter />) test('Params with unreserved characters work in path and query', async () => { const screen = getScreen() act(() => navigate(routes.params({ value: 'example.com', q: 'example.com' })) ) await waitFor(() => { expect( screen.queryByText('param example.comexample.com') ).toBeInTheDocument() expect( screen.queryByText('hookparams example.com?example.com') ).toBeInTheDocument() }) }) test('Params with reserved characters work in path and query', async () => { const screen = getScreen() act(() => navigate(routes.params({ value: 'example!com', q: 'example!com' })) ) await waitFor(() => { expect( screen.queryByText('param example!comexample!com') ).toBeInTheDocument() expect( screen.queryByText('hookparams example!com?example!com') ).toBeInTheDocument() }) }) test('Params with unsafe characters work in query, are escaped in path', async () => { const screen = getScreen() act(() => navigate(routes.params({ value: 'example com', q: 'example com' })) ) await waitFor(() => { expect( screen.queryByText('param example%20comexample com') ).toBeInTheDocument() expect( screen.queryByText('hookparams example%20com?example com') ).toBeInTheDocument() }) }) test('Character / is valid as part of a param in query', async () => { const screen = getScreen() act(() => navigate(routes.params({ value: 'example', q: 'example/com' }))) await waitFor(() => { expect(screen.queryByText('param exampleexample/com')).toBeInTheDocument() expect( screen.queryByText('hookparams example?example/com') ).toBeInTheDocument() }) }) test('Character / is not captured as part of a param in path', async () => { const screen = getScreen() act(() => navigate(routes.params({ value: 'example/com', q: 'example/com' })) ) await waitFor(() => screen.getByText('404')) }) test('navigate to redirect2 should forward params with unreserved characters', async () => { const screen = getScreen() act(() => navigate('/redirect2/example.com?q=example.com')) await waitFor(() => screen.getByText(/param example.comexample.com/i)) }) test('navigate to redirect2 should forward params with escaped characters', async () => { const screen = getScreen() act(() => navigate('/redirect2/example!com?q=example!com')) await waitFor(() => screen.getByText(/param example!comexample!com/i)) }) }) describe('query params should not override path params', () => { const ParamPage = ({ id, contactId }: { id: number; contactId: number }) => { const params = useParams() return ( <div> <p>param {`${id},${contactId}`}</p> <p>hookparams {`${params.id},${params.contactId}`}</p> </div> ) } const TestRouter = () => ( <Router> <Route path="/user/{id:Int}/contact/{contactId:Int}" page={ParamPage} name="contact" /> </Router> ) const getScreen = () => render(<TestRouter />) test('query params of same key as path params should not override path params', async () => { const screen = getScreen() act(() => navigate('/user/1/contact/2?contactId=two')) await waitFor(() => { expect(screen.queryByText('param 1,2')).toBeInTheDocument() expect(screen.queryByText('hookparams 1,2')).toBeInTheDocument() }) }) }) test('unauthenticated user is redirected away from private page', async () => { const TestRouter = () => ( <Router> <Route path="/" page={HomePage} name="home" /> <Route path="/login" page={LoginPage} name="login" /> <Route path="/about" page={AboutPage} name="about" /> <PrivateSet unauthenticated="login"> <Route path="/private" page={PrivatePage} name="private" /> </PrivateSet> </Router> ) const screen = render(<TestRouter />) // starts on home page await waitFor(() => screen.getByText(/Home Page/i)) // navigate to private page // should redirect to login act(() => navigate(routes.private())) await waitFor(() => { expect(screen.queryByText(/Private Page/i)).not.toBeInTheDocument() screen.getByText(/Login Page/i) expect(window.location.pathname).toBe('/login') expect(window.location.search).toBe('?redirectTo=/private') }) }) test('unauthenticated user is redirected including search params', async () => { const TestRouter = () => ( <Router> <Route path="/" page={HomePage} name="home" /> <Route path="/login" page={LoginPage} name="login" /> <PrivateSet unauthenticated="login"> <Route path="/private" page={PrivatePage} name="private" /> </PrivateSet> </Router> ) const screen = render(<TestRouter />) // starts on home page await waitFor(() => screen.getByText(/Home Page/i)) // navigate to private page // should redirect to login act(() => navigate(routes.private({ bazinga: 'yeah' }))) await waitFor(() => { expect(screen.queryByText(/Private Page/i)).not.toBeInTheDocument() expect(window.location.pathname).toBe('/login') expect(window.location.search).toBe( `?redirectTo=/private${encodeURIComponent('?bazinga=yeah')}` ) screen.getByText(/Login Page/i) }) }) test('authenticated user can access private page', async () => { const TestRouter = () => ( <Router useAuth={mockUseAuth({ isAuthenticated: true })}> <Route path="/" page={HomePage} name="home" /> <PrivateSet unauthenticated="home"> <Route path="/private" page={PrivatePage} name="private" /> </PrivateSet> </Router> ) const screen = render(<TestRouter />) // starts on home page await waitFor(() => screen.getByText(/Home Page/i)) // navigate to private page // should not redirect act(() => navigate(routes.private())) await waitFor(() => { expect(screen.getByText(/Private Page/)).toBeInTheDocument() expect(screen.queryByText(/Home Page/)).not.toBeInTheDocument() }) }) test('can display a loading screen whilst waiting for auth', async () => { const TestRouter = () => ( <Router useAuth={mockUseAuth({ isAuthenticated: false, loading: true })}> <Route path="/" page={HomePage} name="home" /> <PrivateSet unauthenticated="home" whileLoadingAuth={() => <>Authenticating...</>} > <Route path="/private" page={PrivatePage} name="private" /> </PrivateSet> </Router> ) const screen = render(<TestRouter />) // starts on home page await waitFor(() => screen.getByText(/Home Page/i)) // navigate to private page // should not redirect act(() => navigate(routes.private())) await waitFor(() => { expect(screen.getByText(/Authenticating.../)).toBeInTheDocument() expect(screen.queryByText(/Home Page/)).not.toBeInTheDocument() }) }) test('can display a loading screen with a hook', async () => { const HookLoader = () => { const [showStill, setShowStill] = useState(false) useEffect(() => { const timer = setTimeout(() => setShowStill(true), 100) return () => clearTimeout(timer) }, []) return <>{showStill ? 'Still authenticating...' : 'Authenticating...'}</> } const TestRouter = () => ( <Router useAuth={mockUseAuth({ isAuthenticated: false, loading: true, loadingTimeMs: 700, })} > <Route path="/" page={HomePage} name="home" /> <PrivateSet unauthenticated="home" whileLoadingAuth={HookLoader}> <Route path="/private" page={PrivatePage} name="private" /> </PrivateSet> </Router> ) const screen = render(<TestRouter />) // starts on home page await waitFor(() => screen.getByText(/Home Page/i)) // navigate to private page // should not redirect act(() => navigate(routes.private())) await waitFor(() => { expect(screen.getByText(/Authenticating.../)).toBeInTheDocument() expect(screen.queryByText(/Home Page/)).not.toBeInTheDocument() expect(screen.queryByText(/Private Page/)).not.toBeInTheDocument() }) await waitFor(() => { expect(screen.getByText(/Still authenticating.../)).toBeInTheDocument() expect(screen.queryByText(/Home Page/)).not.toBeInTheDocument() expect(screen.queryByText(/Private Page/)).not.toBeInTheDocument() }) }) test('inits routes two private routes with a space in between and loads as expected', async () => { const TestRouter = () => ( <Router> <Route path="/" page={HomePage} name="home" /> <Route path="/about" page={AboutPage} name="about" /> <Route path="/redirect" page={RedirectPage} name="redirect" /> <PrivateSet unauthenticated="home"> <Route path="/private" page={PrivatePage} name="private" />{' '} <Route path="/another-private" page={PrivatePage} name="private" /> </PrivateSet> <Route path="/param-test/:value" page={({ value }: { value: string }) => <div>param {value}</div>} name="params" /> </Router> ) const screen = render(<TestRouter />) // starts on home page await waitFor(() => screen.getByText(/Home Page/i)) }) test('supports <Set>', async () => { const GlobalLayout = ({ children }: LayoutProps) => ( <div> <h1>Global Layout</h1> {children} </div> ) const TestRouter = () => ( <Router> <Set wrap={GlobalLayout}> <Route path="/" page={HomePage} name="home" /> <Route path="/about" page={AboutPage} name="about" /> <Route path="/redirect" page={RedirectPage} name="redirect" /> <PrivateSet unauthenticated="home"> <Route path="/private" page={PrivatePage} name="private" /> <Route path="/another-private" page={PrivatePage} name="anotherPrivate" /> </PrivateSet> </Set> </Router> ) const screen = render(<TestRouter />) await waitFor(() => screen.getByText(/Global Layout/i)) await waitFor(() => screen.getByText(/Home Page/i)) }) test('can use named routes for navigating', async () => { const MainLayout = ({ children }: LayoutProps) => { return ( <div> <h1>Main Layout</h1> <Link to={routes.home()}>Home-link</Link> <Link to={routes.about()}>About-link</Link> <hr /> {children} </div> ) } const TestRouter = () => ( <Router> <Set wrap={MainLayout}> <Route path="/" page={HomePage} name="home" /> <Route path="/about" page={AboutPage} name="about" /> </Set> </Router> ) const screen = render(<TestRouter />) // starts on home page, with MainLayout await waitFor(() => screen.getByText(/Home Page/)) await waitFor(() => screen.getByText(/Main Layout/)) fireEvent.click(screen.getByText('About-link')) await waitFor(() => screen.getByText(/About Page/)) }) test('renders only active path', async () => { const AboutLayout = ({ children }: LayoutProps) => { return ( <div> <h1>About Layout</h1> <hr /> {children} </div> ) } const LoginLayout = ({ children }: LayoutProps) => { return ( <div> <h1>Login Layout</h1> <hr /> {children} </div> ) } const TestRouter = () => ( <Router> <Route path="/" page={HomePage} name="home" /> <Set wrap={AboutLayout}> <Route path="/about" page={AboutPage} name="about" /> </Set> <Set wrap={LoginLayout}> <Route path="/login" page={LoginPage} name="login" /> </Set> </Router> ) const screen = render(<TestRouter />) // starts on home page, with no layout await waitFor(() => screen.getByText(/Home Page/)) expect(screen.queryByText('About Layout')).not.toBeInTheDocument() expect(screen.queryByText('Login Layout')).not.toBeInTheDocument() // go to about page, with only about layout act(() => navigate(routes.about())) await waitFor(() => screen.getByText(/About Page/)) expect(screen.queryByText('About Layout')).toBeInTheDocument() expect(screen.queryByText('Login Layout')).not.toBeInTheDocument() // go to login page, with only login layout act(() => navigate(routes.login())) await waitFor(() => screen.getByText(/Login Page/)) expect(screen.queryByText('About Layout')).not.toBeInTheDocument() expect(screen.queryByText('Login Layout')).toBeInTheDocument() }) test('renders first matching route only', async () => { const ParamPage = ({ param }: { param: string }) => <div>param {param}</div> const TestRouter = () => ( <Router> <Route path="/" page={HomePage} name="home" /> <Route path="/about" page={AboutPage} name="about" /> <Route path="/{param}" page={ParamPage} name="param" /> </Router> ) const screen = render(<TestRouter />) await waitFor(() => screen.getByText(/Home Page/)) // go to about page, and make sure that's the only page rendered act(() => navigate(routes.about())) await waitFor(() => screen.getByText('About Page')) expect(screen.queryByText(/param/)).not.toBeInTheDocument() }) test('renders first matching route only, even if multiple routes have the same name', async () => { const ParamPage = ({ param }: { param: string }) => <div>param {param}</div> const AboutTwoPage = () => <h1>About Two Page</h1> const TestRouter = () => ( <Router> <Route path="/" page={HomePage} name="home" /> <Route path="/about" page={AboutPage} name="about" /> <Route path="/{param}" page={ParamPage} name="about" /> <Route path="/about" page={AboutTwoPage} name="about" /> <Route path="/about" page={AboutPage} name="about" /> </Router> ) const screen = render(<TestRouter />) await waitFor(() => screen.getByText(/Home Page/)) // go to about page, and make sure that's the only page rendered act(() => navigate(routes.about())) // `getByText` will throw an error if more than one node is found // which is perfect, because that's exactly what we want to test await waitFor(() => screen.getByText('About Page')) expect(screen.queryByText('param')).not.toBeInTheDocument() expect(screen.queryByText('About Two Page')).not.toBeInTheDocument() }) test('renders first matching route only, also with PrivateSet', async () => { const ParamPage = ({ param }: { param: string }) => <div>param {param}</div> const TestRouter = () => ( <Router> <Route path="/" page={HomePage} name="home" /> <Route path="/login" page={LoginPage} name="login" /> <Route path="/about" page={AboutPage} name="about" /> <PrivateSet unauthenticated="login"> <Route path="/{param}" page={ParamPage} name="param" /> </PrivateSet> </Router> ) const screen = render(<TestRouter />) await waitFor(() => screen.getByText(/Home Page/)) // go to about page, and make sure that's the only page rendered act(() => navigate(routes.about())) await waitFor(() => screen.getByText('About Page')) expect(screen.queryByText(/param/)).not.toBeInTheDocument() }) test('renders first matching route only, also with param path outside PrivateSet', async () => { const ParamPage = ({ param }: { param: string }) => <div>param {param}</div> const TestRouter = () => ( <Router useAuth={mockUseAuth({ isAuthenticated: true })}> <Route path="/" page={HomePage} name="home" /> <PrivateSet unauthenticated="login"> <Route path="/private" page={PrivatePage} name="private" /> </PrivateSet> <Route path="/{param}" page={ParamPage} name="param" /> </Router> ) const screen = render(<TestRouter />) await waitFor(() => screen.getByText(/Home Page/)) // go to about page, and make sure that's the only page rendered act(() => navigate(routes.private())) await waitFor(() => screen.getByText('Private Page')) expect(screen.queryByText(/param/)).not.toBeInTheDocument() }) test('params should never be an empty object', async () => { const ParamPage = () => { const params = useParams() expect(params).not.toEqual({}) return null } const TestRouter = () => ( <Router> <Route path="/test/{documentId}" page={ParamPage} name="param" /> </Router> ) act(() => navigate('/test/1')) render(<TestRouter />) }) test('params should never be an empty object in Set', async () => { const ParamPage = () => { return <div>Param Page</div> } const SetWithUseParams = ({ children }: LayoutProps) => { const params = useParams() expect(params).not.toEqual({}) return <>{children}</> } const TestRouter = () => ( <Router> <Set wrap={SetWithUseParams}> <Route path="/test/{documentId}" page={ParamPage} name="param" /> </Set> </Router> ) act(() => navigate('/test/1')) const screen = render(<TestRouter />) await waitFor(() => screen.getByText('Param Page')) }) test('params should never be an empty object in Set with waitFor (I)', async () => { const ParamPage = () => { const { documentId } = useParams() return <>documentId: {documentId}</> } const SetWithUseParams = ({ children }: LayoutProps) => { const params = useParams() // 1st run: { documentId: '1' } // 2nd run: { documentId: '2' } expect(params).not.toEqual({}) return <>{children}</> } const TestRouter = () => ( <Router> <Set wrap={SetWithUseParams}> <Route path="/test/{documentId}" page={ParamPage} name="param" /> </Set> <Route path="/" page={() => <Redirect to="/test/2" />} name="home" /> </Router> ) act(() => navigate('/test/1')) const screen = render(<TestRouter />) await waitFor(() => screen.getByText(/documentId: 1/)) act(() => navigate('/')) await waitFor(() => screen.getByText(/documentId: 2/)) }) test('params should never be an empty object in Set without waitFor (II)', async () => { const ParamPage = () => { const { documentId } = useParams() return <>documentId: {documentId}</> } const SetWithUseParams = ({ children }: LayoutProps) => { const params = useParams() // 1st run: { documentId: '1' } // 2nd run: { documentId: '2' } expect(params).not.toEqual({}) return <>{children}</> } const TestRouter = () => ( <Router> <Set wrap={SetWithUseParams}> <Route path="/test/{documentId}" page={ParamPage} name="param" /> </Set> <Route path="/" page={() => <Redirect to="/test/2" />} name="home" /> </Router> ) act(() => navigate('/test/1')) const screen = render(<TestRouter />) act(() => navigate('/')) await waitFor(() => screen.getByText(/documentId: 2/)) }) test('Set is not rendered for unauthenticated user.', async () => { const ParamPage = () => { // This should never be called. We should be redirected to login instead. expect(false).toBe(true) return null } const SetWithUseParams = ({ children }: LayoutProps) => { // This should never be called. We should be redirected to login instead. expect(false).toBe(true) return <>{children}</> } const TestRouter = () => ( <Router> <PrivateSet wrap={SetWithUseParams} unauthenticated="login"> <Route path="/test/{documentId}" page={ParamPage} name="param" /> </PrivateSet> <Route path="/" page={HomePage} name="home" /> <Route path="/login" page={() => <div>auth thyself</div>} name="login" /> </Router> ) // Go to home page and start loading // Wait until it has loaded // Go to /test/1 and start loading // Get redirected to /login const screen = render(<TestRouter />) await waitFor(() => screen.getByText('Home Page')) act(() => navigate('/test/1')) await waitFor(() => screen.getByText(/auth thyself/)) }) test('Set is not rendered for unauthenticated user on direct navigation', async () => { const ParamPage = () => { // This should never be called. We should be redirected to login instead. expect(false).toBe(true) return null } const SetWithUseParams = ({ children }: LayoutProps) => { // This should never be called. We should be redirected to login instead. expect(false).toBe(true) return <>{children}</> } const TestRouter = () => ( <Router> {/* Keeping this around so we don't accidentally break the `private` prop on Set until we're ready to remove it */} <Set private wrap={SetWithUseParams} unauthenticated="login"> <Route path="/test/{documentId}" page={ParamPage} name="param" /> </Set> <Route path="/" page={HomePage} name="home" /> <Route path="/login" page={() => <div>auth thyself</div>} name="login" /> </Router> ) act(() => navigate('/test/1')) const screen = render(<TestRouter />) await waitFor(() => screen.getByText(/auth thyself/)) }) // TODO: Remove this entire test once we remove the `<Private>` component test('Private is an alias for Set private', async () => { interface PrivateLayoutProps { children: React.ReactNode theme: string } const PrivateLayout = ({ children, theme }: PrivateLayoutProps) => ( <div> <h1>Private Layout ({theme})</h1> {children} </div> ) const TestRouter = () => ( <Router useAuth={mockUseAuth({ isAuthenticated: true })}> <Route path="/" page={HomePage} name="home" /> <Private<PrivateLayoutProps> wrap={PrivateLayout} unauthenticated="home" theme="dark" > <Route path="/private" page={PrivatePage} name="private" /> </Private> </Router> ) const screen = render(<TestRouter />) await waitFor(() => screen.getByText(/Home Page/i)) act(() => navigate('/private')) await waitFor(() => screen.getByText(/Private Layout \(dark\)/)) await waitFor(() => screen.getByText(/Private Page/)) }) test('redirect to last page', async () => { const TestRouter = () => ( <Router> <Route path="/" page={HomePage} name="home" /> <Route path="/about" page={AboutPage} name="about" /> <PrivateSet unauthenticated="login"> <Route path="/private" page={PrivatePage} name="private" /> </PrivateSet> <Route path="/login" page={LoginPage} name="login" /> </Router> ) const screen = render(<TestRouter />) // starts on home page await waitFor(() => screen.getByText(/Home Page/i)) // navigate to private page // should redirect to login act(() => navigate(routes.private())) await waitFor(() => { expect(screen.queryByText(/Private Page/i)).not.toBeInTheDocument() screen.getByText('Login Page') expect(window.location.pathname).toBe('/login') expect(window.location.search).toBe('?redirectTo=/private') }) }) test('no location match means nothing is rendered', async () => { const TestRouter = () => ( <Router> <Route path="/" page={HomePage} name="home" /> </Router> ) const screen = render(<TestRouter />) // starts on home page await waitFor(() => screen.getByText(/Home Page/i)) // navigate page that doesn't exist act(() => navigate('/not/found')) // wait for rendering // Otherwise adding a NotFound route still makes this test pass await new Promise((r) => setTimeout(r, 200)) expect(screen.container).toMatchInlineSnapshot('<div />') }) test('jump to new route, then go back', async () => { const HelpPage = () => <h1>Help Page</h1> const TestRouter = () => ( <Router> <Route path="/" page={HomePage} name="home" /> <Route path="/login" page={LoginPage} name="login" /> <Route path="/about" page={AboutPage} name="about" /> <Route path="/help" page={HelpPage} name="help" /> </Router> ) const screen = render(<TestRouter />) // starts on home page await waitFor(() => screen.getByText('Home Page')) act(() => navigate(routes.about())) await waitFor(() => screen.getByText('About Page')) act(() => navigate(routes.help(), { replace: true })) await waitFor(() => screen.getByText('Help Page')) act(() => back()) await waitFor(() => screen.getByText('Home Page')) }) test('redirect replacing route', async () => { const ListWithDefaultParamsPage = (props: { _limit: string }) => { if (props['_limit']) { return <h1>List Page</h1> } return <Redirect to="/list?_limit=10" options={{ replace: true }} /> } const TestRouter = () => ( <Router> <Route path="/" page={HomePage} name="home" /> <Route path="/list" page={ListWithDefaultParamsPage} name="list" /> </Router> ) const screen = render(<TestRouter />) // starts on home page await waitFor(() => screen.getByText('Home Page')) // This will navigate to /list, which will then redirect to /list?_limit=10 // which will render `<h1>List Page</h1>` act(() => navigate(routes.list())) await waitFor(() => screen.getByText('List Page')) act(() => back()) // without options.replace = true in Redirect, back would go to List Page await waitFor(() => screen.getByText('Home Page')) }) describe('trailing slashes', () => { const TSNeverRouter = () => ( <Router trailingSlashes="never"> <Route path="/" page={HomePage} name="home" /> <Route path="/about" page={AboutPage} name="about" /> <Route notfound page={NotFoundPage} /> </Router> ) const getTSNeverScreen = () => render(<TSNeverRouter />) test('starts on home page', async () => { const screen = getTSNeverScreen() await waitFor(() => screen.getByText(/Home Page/i)) }) test('strips trailing slash on navigating to about page', async () => { const screen = getTSNeverScreen() act(() => navigate('/about/')) await waitFor(() => screen.getByText(/About Page/i)) }) const TSAlwaysRouter = () => ( <Router trailingSlashes="always"> <Route path="/" page={HomePage} name="home" /> <Route path="/about/" page={AboutPage} name="about" /> <Route notfound page={NotFoundPage} /> </Router> ) const getTSAlwaysScreen = () => render(<TSAlwaysRouter />) test('starts on home page', async () => { const screen = getTSAlwaysScreen() await waitFor(() => screen.getByText(/Home Page/i)) }) test('adds trailing slash on navigating to about page', async () => { const screen = getTSAlwaysScreen() act(() => navigate('/about')) await waitFor(() => screen.getByText(/About Page/i)) }) const TSPreserveRouter = () => ( <Router trailingSlashes="preserve"> <Route path="/" page={HomePage} name="home" /> <Route path="/about" page={AboutPage} name="about" /> <Route path="/contact/" page={() => <h1>Contact Page</h1>} name="about" /> <Route notfound page={NotFoundPage} /> </Router> ) const getTSPreserveScreen = () => render(<TSPreserveRouter />) test('starts on home page', async () => { const screen = getTSPreserveScreen() await waitFor(() => screen.getByText(/Home Page/i)) }) test('navigates to about page as is', async () => { const screen = getTSPreserveScreen() act(() => navigate('/about')) await waitFor(() => screen.getByText(/About Page/i)) }) test('navigates to contact page as is', async () => { const screen = getTSPreserveScreen() act(() => navigate('/contact/')) await waitFor(() => screen.getByText(/Contact Page/i)) }) }) test('params should be updated if navigated to different route with same page', async () => { const UserPage = ({ id }: { id?: number }) => { const { id: idFromContext } = useParams() return ( <> <p>param {id ? id : 'no-id'}</p> <p>hookparams {idFromContext ? idFromContext : 'no-param-id'} </p> </> ) } const TestRouter = () => ( <Router> <Route path="/user" page={UserPage} name="allUsers" /> <Route path="/user/{id:Int}" page={UserPage} name="user" /> </Router> ) const screen = render(<TestRouter />) act(() => navigate('/user')) // Wait for page load await waitFor(() => screen.getByText('param no-id')) act(() => navigate('/user/99')) await waitFor(() => { expect(screen.queryByText('param 99')).toBeInTheDocument() expect(screen.queryByText('hookparams 99')).toBeInTheDocument() }) }) test('should handle ref and key as search params', async () => { const ParamsPage = () => { const { ref, key } = useParams() return <p>{JSON.stringify({ ref, key })}</p> } const TestRouter = () => ( <Router> <Route path="/params" page={ParamsPage} name="params" /> </Router> ) const screen = render(<TestRouter />) act(() => navigate('/params?ref=1&key=2')) await waitFor(() => { expect(screen.queryByText(`{"ref":"1","key":"2"}`)).toBeInTheDocument() }) }) describe('Unauthorized redirect error messages', () => { let err: typeof console.error beforeAll(() => { err = console.error console.error = jest.fn() }) afterAll(() => { console.error = err }) test('PrivateSet with unauthenticated prop with nonexisting page', async () => { const TestRouter = ({ authenticated }: { authenticated?: boolean }) => ( <Router useAuth={mockUseAuth({ isAuthenticated: authenticated })}> <Route path="/" page={HomePage} name="home" /> <PrivateSet unauthenticated="does-not-exist"> <Route path="/private" page={PrivatePage} name="private" /> </PrivateSet> </Router> ) act(() => navigate('/private')) expect(() => render(<TestRouter authenticated={false} />)).toThrow( 'We could not find a route named does-not-exist' ) }) test('PrivateSet redirecting to page that needs parameters', async () => { const TestRouter = ({ authenticated }: { authenticated?: boolean }) => ( <Router useAuth={mockUseAuth({ isAuthenticated: authenticated })}> <Route path="/" page={HomePage} name="home" /> <Route path="/param-test/{value}" page={ParamPage} name="params" /> <PrivateSet unauthenticated="params"> <Route path="/private" page={PrivatePage} name="private" /> </PrivateSet> </Router> ) act(() => navigate('/private')) expect(() => render(<TestRouter authenticated={false} />)).toThrow( 'Redirecting to route "params" would require route parameters, which ' + 'currently is not supported. Please choose a different route' ) }) }) describe('Multiple nested private sets', () => { const HomePage = () => <h1>Home Page</h1> const PrivateNoRolesAssigned = () => <h1>Private No Roles Page</h1> const PrivateEmployeePage = () => <h1>Private Employee Page</h1> const PrivateAdminPage = () => <h1>Private Admin Page</h1> interface LevelLayoutProps { children: React.ReactNode level: string } const LevelLayout = ({ children, level }: LevelLayoutProps) => ( <div> Level: {level} {children} </div> ) const TestRouter = ({ useAuthMock }: { useAuthMock: UseAuth }) => ( <Router useAuth={useAuthMock}> <Route path="/" page={HomePage} name="home" /> <PrivateSet<LevelLayoutProps> unauthenticated="home" level="1" wrap={LevelLayout} > <Route path="/no-roles-assigned" page={PrivateNoRolesAssigned} name="noRolesAssigned" /> <PrivateSet unauthenticated="noRolesAssigned" roles={['ADMIN', 'EMPLOYEE']} > <PrivateSet unauthenticated="privateAdmin" roles={['EMPLOYEE']}> <Route path="/employee" page={PrivateEmployeePage} name="privateEmployee" /> </PrivateSet> <PrivateSet unauthenticated="privateEmployee" roles={['ADMIN']}> <Route path="/admin" page={PrivateAdminPage} name="privateAdmin" /> </PrivateSet> </PrivateSet> </PrivateSet> </Router> ) test('is authenticated but does not have matching roles', async () => { const screen = render( <TestRouter useAuthMock={mockUseAuth({ isAuthenticated: true, hasRole: false, })} /> ) act(() => navigate('/employee')) await waitFor(() => { expect(screen.queryByText(`Private No Roles Page`)).toBeInTheDocument() expect(screen.queryByText(`Level: 1`)).toBeInTheDocument() }) }) test('is not authenticated', async () => { const screen = render( <TestRouter useAuthMock={mockUseAuth({ isAuthenticated: false, hasRole: false, })} /> ) act(() => navigate('/employee')) await waitFor(() => { expect(screen.queryByText(`Home Page`)).toBeInTheDocument() expect(screen.queryByText(`Level`)).not.toBeInTheDocument() }) }) test('is authenticated and has a matching role', async () => { const screen = render( <TestRouter useAuthMock={mockUseAuth({ isAuthenticated: true, hasRole: (role) => { return role.includes('ADMIN') }, })} /> ) act(() => navigate('/admin')) await waitFor(() => { expect(screen.queryByText(`Private Admin Page`)).toBeInTheDocument() }) }) test('returns the correct page if has a matching role', async () => { const screen = render( <TestRouter useAuthMock={mockUseAuth({ isAuthenticated: true, hasRole: (role) => { return role.includes('ADMIN') }, })} /> ) act(() => navigate('/admin')) await waitFor(() => { expect(screen.queryByText(`Private Admin Page`)).toBeInTheDocument() }) }) }) describe('Multiple nested sets', () => { const HomePage = () => <h1>Home Page</h1> const Page = () => <h1>Page</h1> interface DebugLayoutProps { children: React.ReactNode theme: string otherProp?: string level: string } const DebugLayout = (props: DebugLayoutProps) => { return ( <div> <p>Theme: {props.theme}</p> <p>Other Prop: {props.otherProp}</p> <p>Page Level: {props.level}</p> {props.children} </div> ) } const TestRouter = () => ( <Router> <Route path="/" page={HomePage} name="home" /> <Set<DebugLayoutProps> level="1" theme="blue" wrap={DebugLayout}> <Route path="/level1" page={Page} name="level1" /> <Set level="2" theme="red" otherProp="bazinga"> <Route path="/level2" page={Page} name="level2" /> <Set level="3" theme="green"> <Route path="/level3" page={Page} name="level3" /> </Set> </Set> </Set> </Router> ) test('level 1, matches expected props', async () => { act(() => navigate('/level1')) const screen = render(<TestRouter />) await waitFor(() => { expect(screen.queryByText('Theme: blue')).toBeInTheDocument() expect(screen.queryByText('Other Prop:')).toBeInTheDocument() expect(screen.queryByText('Page Level: 1')).toBeInTheDocument() }) }) test('level 2, should not affect level 1 set props', async () => { act(() => navigate('/level2')) const screen = render(<TestRouter />) await waitFor(() => { expect(screen.queryByText('Page')).toBeInTheDocument() expect(screen.queryByText('Theme: blue')).toBeInTheDocument() expect(screen.queryByText('Other Prop:')).toBeInTheDocument() expect(screen.queryByText('Page Level: 1')).toBeInTheDocument() }) }) test('level 3, should override level 1 & 2 and pass through other props', async () => { const screen = render(<TestRouter />) act(() => navigate('/level3')) await waitFor(() => { expect(screen.queryByText('Theme: blue')).toBeInTheDocument() expect(screen.queryByText('Other Prop:')).toBeInTheDocument() expect(screen.queryByText('Page Level: 1')).toBeInTheDocument() }) }) })
5,816
0
petrpan-code/redwoodjs/redwood/packages/router/src
petrpan-code/redwoodjs/redwood/packages/router/src/__tests__/set.test.tsx
import * as React from 'react' import type { ReactNode } from 'react' import { act, render, waitFor } from '@testing-library/react' import '@testing-library/jest-dom/extend-expect' import { navigate } from '../history' import { Route, Router } from '../router' import { Set } from '../Set' // SETUP interface LayoutProps { children: ReactNode } const ChildA = () => <h1>ChildA</h1> const ChildB = () => <h1>ChildB</h1> const ChildC = () => <h1>ChildC</h1> const GlobalLayout = ({ children }: LayoutProps) => ( <div> <h1>Global Layout</h1> {children} <footer>This is a footer</footer> </div> ) const CustomWrapper = ({ children }: LayoutProps) => ( <div> <h1>Custom Wrapper</h1> {children} <p>Custom Wrapper End</p> </div> ) const BLayout = ({ children }: LayoutProps) => ( <div> <h1>Layout for B</h1> {children} </div> ) beforeEach(() => { window.history.pushState({}, '', '/') }) test('wraps components in other components', async () => { const TestSet = () => ( <Router> <Set wrap={[CustomWrapper, GlobalLayout]}> <ChildA /> <Set wrap={BLayout}> <Route path="/" page={ChildB} name="childB" /> </Set> </Set> <ChildC /> </Router> ) const screen = render(<TestSet />) await waitFor(() => screen.getByText('ChildB')) expect(screen.container).toMatchInlineSnapshot(` <div> <div> <h1> Custom Wrapper </h1> <div> <h1> Global Layout </h1> <div> <h1> Layout for B </h1> <h1> ChildB </h1> <div aria-atomic="true" aria-live="assertive" id="redwood-announcer" role="alert" style="position: absolute; top: 0px; width: 1px; height: 1px; padding: 0px; overflow: hidden; clip: rect(0px, 0px, 0px, 0px); white-space: nowrap; border: 0px;" /> </div> <footer> This is a footer </footer> </div> <p> Custom Wrapper End </p> </div> </div> `) }) test('passes props to wrappers', async () => { interface Props { propOne: string propTwo: string children: ReactNode } const PropWrapper = ({ children, propOne, propTwo }: Props) => ( <div> <h1>Prop Wrapper</h1> <p>1:{propOne}</p> <p>2:{propTwo}</p> {children} </div> ) const PropWrapperTwo = ({ children }: Props) => ( <div> <h1>Prop Wrapper Two</h1> {children} <footer>This is a footer</footer> </div> ) const TestSet = () => ( <Router> <Set wrap={[PropWrapper, PropWrapperTwo]} propOne="une" propTwo="deux"> <Route path="/" page={ChildA} name="childA" /> </Set> </Router> ) const screen = render(<TestSet />) await waitFor(() => screen.getByText('ChildA')) expect(screen.container).toMatchInlineSnapshot(` <div> <div> <h1> Prop Wrapper </h1> <p> 1: une </p> <p> 2: deux </p> <div> <h1> Prop Wrapper Two </h1> <h1> ChildA </h1> <div aria-atomic="true" aria-live="assertive" id="redwood-announcer" role="alert" style="position: absolute; top: 0px; width: 1px; height: 1px; padding: 0px; overflow: hidden; clip: rect(0px, 0px, 0px, 0px); white-space: nowrap; border: 0px;" /> <footer> This is a footer </footer> </div> </div> </div> `) }) describe('Navigating Sets', () => { const HomePage = () => <h1>Home Page</h1> const Page = () => <h1>Page</h1> test('Sets should not cause a re-mount of wrap components when navigating within the set', async () => { const layoutOneMount = jest.fn() const layoutOneUnmount = jest.fn() const Layout1 = ({ children }: LayoutProps) => { React.useEffect(() => { // Called on mount and re-mount of this layout layoutOneMount() return () => { layoutOneUnmount() } }, []) return ( <> <p>ONE</p> {children} </> ) } const Routes = () => ( <Router> <Route path="/" page={HomePage} name="home" /> <Set wrap={Layout1}> <Route path="/posts/new" page={Page} name="newPost" /> <Route path="/posts/{id:Int}/edit" page={Page} name="editPost" /> <Route path="/posts/{id:Int}" page={Page} name="post" /> <Route path="/posts" page={Page} name="posts" /> </Set> </Router> ) render(<Routes />) act(() => navigate('/')) act(() => navigate('/posts')) act(() => navigate('/posts/new')) act(() => navigate('/posts')) act(() => navigate('/posts/1')) act(() => navigate('/posts/new')) act(() => navigate('/posts')) // Navigating into, and then within Layout1 should not cause a re-mount expect(layoutOneMount).toHaveBeenCalledTimes(1) expect(layoutOneUnmount).toHaveBeenCalledTimes(0) }) test('Sets should make wrap components remount when navigating between separate sets with the same wrap component', async () => { const layoutOneMount = jest.fn() const layoutOneUnmount = jest.fn() const Layout1 = ({ children }: LayoutProps) => { React.useEffect(() => { // Called on mount and re-mount of this layout layoutOneMount() return () => { layoutOneUnmount() } }, []) return ( <> <p>ONE</p> {children} </> ) } const Routes = () => ( <Router> <Route path="/" page={HomePage} name="home" /> <Set wrap={Layout1}> <Route path="/posts" page={Page} name="posts" /> </Set> <Set wrap={Layout1}> <Route path="/comments" page={Page} name="comments" /> </Set> </Router> ) render(<Routes />) act(() => navigate('/')) expect(layoutOneMount).toHaveBeenCalledTimes(0) expect(layoutOneUnmount).toHaveBeenCalledTimes(0) act(() => navigate('/posts')) expect(layoutOneMount).toHaveBeenCalledTimes(1) expect(layoutOneUnmount).toHaveBeenCalledTimes(0) act(() => navigate('/')) expect(layoutOneMount).toHaveBeenCalledTimes(1) expect(layoutOneUnmount).toHaveBeenCalledTimes(1) act(() => navigate('/posts')) expect(layoutOneMount).toHaveBeenCalledTimes(2) expect(layoutOneUnmount).toHaveBeenCalledTimes(1) // This is the real test. Navigating between /posts and /comments should // remount the wrap component because even though it's the same component, // it's in different sets. act(() => navigate('/comments')) expect(layoutOneMount).toHaveBeenCalledTimes(3) expect(layoutOneUnmount).toHaveBeenCalledTimes(2) act(() => navigate('/')) expect(layoutOneMount).toHaveBeenCalledTimes(3) expect(layoutOneUnmount).toHaveBeenCalledTimes(3) }) })
5,817
0
petrpan-code/redwoodjs/redwood/packages/router/src
petrpan-code/redwoodjs/redwood/packages/router/src/__tests__/setContextReuse.test.tsx
import React from 'react' import { act, render, waitFor } from '@testing-library/react' import { Route, Router, navigate } from '../' import { Set } from '../Set' import '@testing-library/jest-dom/extend-expect' const HomePage = () => { return <p>Home Page</p> } interface ContextState { contextValue: string setContextValue: React.Dispatch<React.SetStateAction<string>> } const SetContext = React.createContext<ContextState | undefined>(undefined) const SetContextProvider = ({ children }: { children: React.ReactNode }) => { const [contextValue, setContextValue] = React.useState('initialSetValue') return ( <SetContext.Provider value={{ contextValue, setContextValue }}> {children} </SetContext.Provider> ) } const Ctx1Page = () => { const ctx = React.useContext(SetContext) React.useEffect(() => { ctx?.setContextValue('updatedSetValue') }, [ctx]) return <p>1-{ctx?.contextValue}</p> } const Ctx2Page = () => { const ctx = React.useContext(SetContext) return <p>2-{ctx?.contextValue}</p> } const Ctx3Page = () => { const ctx = React.useContext(SetContext) return <p>3-{ctx?.contextValue}</p> } const Ctx4Page = () => { const ctx = React.useContext(SetContext) return <p>4-{ctx?.contextValue}</p> } const TestRouter = () => { return ( <Router> <Route path="/" page={HomePage} name="home" /> <Set wrap={SetContextProvider}> <Route path="/ctx-1-page" page={Ctx1Page} name="ctx1" /> <Route path="/ctx-2-page" page={Ctx2Page} name="ctx2" /> <Set wrap={SetContextProvider}> <Route path="/ctx-3-page" page={Ctx3Page} name="ctx3" /> </Set> </Set> <Set wrap={SetContextProvider}> <Route path="/ctx-4-page" page={Ctx4Page} name="ctx4" /> </Set> </Router> ) } test("Doesn't destroy <Set> when navigating inside, but does when navigating between", async () => { const screen = render(<TestRouter />) await waitFor(() => screen.getByText('Home Page')) act(() => navigate('/ctx-1-page')) await waitFor(() => screen.getByText('1-updatedSetValue')) act(() => navigate('/ctx-2-page')) await waitFor(() => screen.getByText('2-updatedSetValue')) act(() => navigate('/ctx-3-page')) await waitFor(() => screen.getByText('3-initialSetValue')) act(() => navigate('/ctx-4-page')) await waitFor(() => screen.getByText('4-initialSetValue')) act(() => navigate('/ctx-2-page')) await waitFor(() => screen.getByText('2-initialSetValue')) act(() => navigate('/ctx-1-page')) await waitFor(() => screen.getByText('1-updatedSetValue')) act(() => navigate('/ctx-2-page')) await waitFor(() => screen.getByText('2-updatedSetValue')) act(() => navigate('/ctx-4-page')) await waitFor(() => screen.getByText('4-initialSetValue')) })
5,818
0
petrpan-code/redwoodjs/redwood/packages/router/src
petrpan-code/redwoodjs/redwood/packages/router/src/__tests__/util.test.ts
import { paramsForRoute, matchPath, parseSearch, validatePath, flattenSearchParams, replaceParams, } from '../util' describe('paramsForRoute', () => { it.each([ ['/post/{slug}', [['slug', 'String', '{slug}']]], ['/post/{slug...}', [['slug', 'Glob', '{slug...}']]], ['/id/{id:Int}', [['id', 'Int', '{id:Int}']]], ])('extracts name and type info', (route, info) => { expect(paramsForRoute(route)).toEqual(info) }) }) describe('matchPath', () => { it.each([ ['/post/{id:Int}', '/post/notAnInt'], ['/post/{id:Int}', '/post/2.0'], ['/post/{id:Int}', '/post/.1'], ['/post/{id:Int}', '/post/0.1'], ['/post/{id:Int}', '/post/123abcd'], ['/post/{id:Int}', '/post/abcd123'], ['/blog/{year}/{month:Int}/{day}', '/blog/2019/december/07'], ['/blog/{year}/{month}/{day}', '/blog/2019/07'], ['/posts/{id}/edit', '/posts//edit'], ['/about', '/'], ])('does not match route "%s" with path "%s"', (route, pathname) => { expect(matchPath(route, pathname)).toEqual({ match: false }) }) it('matches valid paths and extracts params correctly', () => { expect(matchPath('/blog/{year}/{month}/{day}', '/blog/2019/12/07')).toEqual( { match: true, params: { day: '07', month: '12', year: '2019' } } ) }) it('transforms a param for Int', () => { expect(matchPath('/post/{id}', '/post/1337')).toEqual({ match: true, params: { id: '1337' }, }) expect(matchPath('/post/{id:Int}', '/post/1337')).toEqual({ match: true, params: { id: 1337 }, }) expect(matchPath('/post/id-{id:Int}', '/post/id-37')).toEqual({ match: true, params: { id: 37 }, }) expect(matchPath('/post/{id:Int}-id', '/post/78-id')).toEqual({ match: true, params: { id: 78 }, }) expect(matchPath('/post/id-{id:Int}-id', '/post/id-789-id')).toEqual({ match: true, params: { id: 789 }, }) expect(matchPath('/{id:Int}/bazinga', '/89/bazinga')).toEqual({ match: true, params: { id: 89 }, }) }) it('transforms a param for Boolean', () => { expect(matchPath('/signedUp/{status:Boolean}', '/signedUp/true')).toEqual({ match: true, params: { status: true, }, }) expect(matchPath('/signedUp/{status:Boolean}', '/signedUp/false')).toEqual({ match: true, params: { status: false, }, }) expect( matchPath('/signedUp/x-{status:Boolean}', '/signedUp/x-false') ).toEqual({ match: true, params: { status: false, }, }) expect( matchPath('/signedUp/{status:Boolean}y', '/signedUp/falsey') ).toEqual({ match: true, params: { status: false, }, }) expect( matchPath('/signedUp/e{status:Boolean}y', '/signedUp/efalsey') ).toEqual({ match: true, params: { status: false, }, }) expect( matchPath('/signedUp/{status:Boolean}', '/signedUp/somethingElse') ).toEqual({ match: false, }) }) it('transforms a param for Floats', () => { expect( matchPath('/version/{floatyMcFloat:Float}', '/version/1.58') ).toEqual({ match: true, params: { floatyMcFloat: 1.58, }, }) expect(matchPath('/version/{floatyMcFloat:Float}', '/version/626')).toEqual( { match: true, params: { floatyMcFloat: 626, }, } ) expect( matchPath('/version/{floatyMcFloat:Float}', '/version/+0.92') ).toEqual({ match: true, params: { floatyMcFloat: 0.92, }, }) expect( matchPath('/version/{floatyMcFloat:Float}', '/version/-5.5') ).toEqual({ match: true, params: { floatyMcFloat: -5.5, }, }) expect(matchPath('/version/{floatyMcFloat:Float}', '/version/4e8')).toEqual( { match: true, params: { floatyMcFloat: 4e8, }, } ) expect( matchPath('/version/{floatyMcFloat:Float}', '/version/noMatchMe') ).toEqual({ match: false, }) }) it('transforms a param for Globs', () => { //single expect(matchPath('/version/{path...}', '/version/path/to/file')).toEqual({ match: true, params: { path: 'path/to/file', }, }) // multiple expect(matchPath('/a/{a...}/b/{b...}/c', '/a/1/2/b/3/4/c')).toEqual({ match: true, params: { a: '1/2', b: '3/4', }, }) // adjacent expect(matchPath('/a/{a...}{b...}/c', '/a/1/2/3/4/c')).toEqual({ match: true, params: { a: '1/2/3/4', b: '', }, }) // adjacent with a slash expect(matchPath('/a/{a...}/{b...}/c', '/a/1/2/3/4/c')).toEqual({ match: true, params: { a: '1/2/3', b: '4', }, }) // prefixed expect(matchPath('/a-{a...}', '/a-1/2')).toEqual({ match: true, params: { a: '1/2', }, }) // suffixed expect(matchPath('/{a...}-a/kittens', '/1/2-a/kittens')).toEqual({ match: true, params: { a: '1/2', }, }) }) it('handles multiple typed params', () => { expect( matchPath( '/dashboard/document/{id:Int}/{version:Float}/edit/{edit:Boolean}/{path...}/terminate', '/dashboard/document/44/1.8/edit/false/path/to/file/terminate' ) ).toEqual({ match: true, params: { id: 44, version: 1.8, edit: false, path: 'path/to/file' }, }) }) }) describe('validatePath', () => { it.each([ { path: 'invalid/route', routeName: 'isInvalid' }, { path: '{id}/invalid/route', routeName: 'isInvalid' }, { path: ' /invalid/route', routeName: 'isInvalid' }, ])( 'rejects "%s" path that does not begin with a slash', ({ path, routeName }) => { expect(() => validatePath(path, routeName)).toThrowError( `Route path for ${routeName} does not begin with a slash: "${path}"` ) } ) it.each([ { path: '/path/to/user profile', routeName: 'hasSpaces' }, { path: '/path/ to/userprofile', routeName: 'hasSpaces' }, { path: '/path/to /userprofile', routeName: 'hasSpaces' }, { path: '/path/to/users/{id: Int}', routeName: 'hasSpaces' }, { path: '/path/to/users/{id :Int}', routeName: 'hasSpaces' }, { path: '/path/to/users/{id : Int}', routeName: 'hasSpaces' }, { path: '/path/to/users/{ id:Int}', routeName: 'hasSpaces' }, { path: '/path/to/users/{id:Int }', routeName: 'hasSpaces' }, { path: '/path/to/users/{ id:Int }', routeName: 'hasSpaces' }, { path: '/path/to/users/{ id : Int }', routeName: 'hasSpaces' }, ])('rejects paths with spaces: "%s"', ({ path, routeName }) => { expect(() => validatePath(path, routeName)).toThrowError( `Route path for ${routeName} contains spaces: "${path}"` ) }) it.each([ { path: '/users/{id}/photos/{id}', routeName: 'hasDuplicateParams' }, { path: '/users/{id}/photos/{id:Int}', routeName: 'hasDuplicateParams' }, { path: '/users/{id:Int}/photos/{id}', routeName: 'hasDuplicateParams' }, { path: '/users/{id:Int}/photos/{id:Int}', routeName: 'hasDuplicateParams', }, ])('rejects path "%s" with duplicate params', ({ path, routeName }) => { expect(() => validatePath(path, routeName)).toThrowError( `Route path contains duplicate parameter: "${path}"` ) }) it.each([ { path: '/users/{id:Int}/photos/{photo_id:Int}', routeName: 'validCorrectPath', }, { path: '/users/{id}/photos/{photo_id}', routeName: 'validCorrectPath' }, { path: '/users/{id}/photos/{photo_id}?format=jpg&w=400&h=400', routeName: 'validCorrectPath', }, { path: '/', routeName: 'validCorrectPath' }, { path: '/404', routeName: 'validCorrectPath' }, { path: '/about', routeName: 'validCorrectPath' }, { path: '/about/redwood', routeName: 'validCorrectPath' }, ])('validates correct path "%s"', ({ path, routeName }) => { expect(() => validatePath(path, routeName)).not.toThrow() }) it.each([ { path: '/path/{ref}', routeName: 'ref' }, { path: '/path/{ref}/bazinga', routeName: 'ref' }, { path: '/path/{ref:Int}', routeName: 'ref' }, { path: '/path/{ref:Int}/bazinga', routeName: 'ref' }, { path: '/path/{key}', routeName: 'key' }, { path: '/path/{key}/bazinga', routeName: 'key' }, { path: '/path/{key:Int}', routeName: 'key' }, { path: '/path/{key:Int}/bazinga', routeName: 'key' }, ])( 'rejects paths with ref or key as path parameters: "%s"', ({ path, routeName }) => { expect(() => validatePath(path, routeName)).toThrowError( [ `Route for ${routeName} contains ref or key as a path parameter: "${path}"`, "`ref` and `key` shouldn't be used as path parameters because they're special React props.", 'You can fix this by renaming the path parameter.', ].join('\n') ) } ) it.each([ { path: '/path/{reff}', routeName: 'validRefKeyVariations' }, { path: '/path/{reff:Int}', routeName: 'validRefKeyVariations' }, { path: '/path/{reff}/bazinga', routeName: 'validRefKeyVariations' }, { path: '/path/{keys}', routeName: 'validRefKeyVariations' }, { path: '/path/{keys:Int}', routeName: 'validRefKeyVariations' }, { path: '/path/key', routeName: 'validRefKeyVariations' }, { path: '/path/key/bazinga', routeName: 'validRefKeyVariations' }, ])( `doesn't reject paths with variations on ref or key as path parameters: "%s"`, ({ path, routeName }) => { expect(() => validatePath(path, routeName)).not.toThrowError() } ) }) describe('parseSearch', () => { it('deals silently with an empty search string', () => { expect(parseSearch('')).toEqual({}) }) it('correctly parses a search string', () => { expect( parseSearch('?search=all+dogs+go+to+heaven&category=movies') ).toEqual({ category: 'movies', search: 'all dogs go to heaven' }) }) }) describe('flattenSearchParams', () => { it('returns a flat array from query string', () => { expect( flattenSearchParams('?search=all+dogs+go+to+heaven&category=movies') ).toEqual([{ search: 'all dogs go to heaven' }, { category: 'movies' }]) }) it('returns an empty array', () => { expect(flattenSearchParams('')).toEqual([]) }) }) describe('replaceParams', () => { it('throws an error on missing params', () => { expect(() => replaceParams('/tags/{tag}', {})).toThrowError( "Missing parameter 'tag' for route '/tags/{tag}' when generating a navigation URL." ) }) it('replaces named parameter with value from the args object', () => { expect(replaceParams('/tags/{tag}', { tag: 'code' })).toEqual('/tags/code') }) it('replaces multiple named parameters with values from the args object', () => { expect( replaceParams('/posts/{year}/{month}/{day}', { year: '2021', month: '09', day: '19', }) ).toEqual('/posts/2021/09/19') }) it('appends extra parameters as search parameters', () => { expect(replaceParams('/extra', { foo: 'foo' })).toEqual('/extra?foo=foo') expect(replaceParams('/tags/{tag}', { tag: 'code', foo: 'foo' })).toEqual( '/tags/code?foo=foo' ) }) it('handles falsy parameter values', () => { expect(replaceParams('/category/{categoryId}', { categoryId: 0 })).toEqual( '/category/0' ) expect(replaceParams('/boolean/{bool}', { bool: false })).toEqual( '/boolean/false' ) expect(() => replaceParams('/undef/{undef}', { undef: undefined }) ).toThrowError( "Missing parameter 'undef' for route '/undef/{undef}' when generating a navigation URL." ) }) it('handles typed params', () => { expect(replaceParams('/post/{id:Int}', { id: 7 })).toEqual('/post/7') expect(replaceParams('/post/{id:Float}', { id: 7 })).toEqual('/post/7') expect(replaceParams('/post/{id:Bool}', { id: true })).toEqual('/post/true') expect(replaceParams('/post/{id:Bool}', { id: false })).toEqual( '/post/false' ) expect(replaceParams('/post/{id:String}', { id: 7 })).toEqual('/post/7') }) it('handles globs', () => { expect(replaceParams('/path/{path...}', { path: 'foo/bar' })).toEqual( '/path/foo/bar' ) expect(replaceParams('/a/{b...}/c/{d...}/e', { b: 1, d: 2 })).toEqual( '/a/1/c/2/e' ) }) })
5,819
0
petrpan-code/redwoodjs/redwood/packages/router/src
petrpan-code/redwoodjs/redwood/packages/router/src/__typetests__/routeParamsTypes.test.ts
import { context, describe, expect, test } from 'tstyche' import type { RouteParams, ParamType } from '../routeParamsTypes' /** * FAQ: * - why aren't you using .toBeAssignable() in all tests? * because {b: string} is assignable to Record, and then test isn't accurate enough * * - why aren't you just checking the entire type? * because sometimes, the parser returns {Params & GenericParams} (and that's ok!), checking the full type will cause failures * * - why are you assigning the const values if you're just checking the types? * for readability: param?.id! everywhere is ugly - it helps with making these tests read like documentation * */ describe('RouteParams<>', () => { test('Single parameters', () => { const simple: RouteParams<'bazinga/{id:Int}'> = { id: 2, } expect(simple.id).type.toBeNumber() }) test('Starts with parameter', () => { const startParam: RouteParams<'/{position:Int}/{driver:Float}/stats'> = { position: 1, driver: 44, } expect(startParam.driver).type.toBeNumber() expect(startParam.position).type.toBeNumber() }) test('Route string with no types defaults to string', () => { const untypedParams: RouteParams<'/blog/{year}/{month}/{day}/{slug}'> = { year: '2020', month: '01', day: '01', slug: 'hello-world', } expect(untypedParams.year).type.toBeString() expect(untypedParams.month).type.toBeString() expect(untypedParams.day).type.toBeString() expect(untypedParams.slug).type.toBeString() }) test('Custom param types', () => { const customParams: RouteParams<'/post/{name:slug}'> = { name: 'hello-world-slug', } expect(customParams.name).type.toBeString() }) test('Parameter inside string', () => { const stringConcat: RouteParams<'/signedUp/e{status:Boolean}y'> = { status: true, } expect(stringConcat.status).type.toBeBoolean() }) test('Multiple Glob route params', () => { const globRoutes: RouteParams<'/from/{fromDate...}/to/{toDate...}'> = { fromDate: '2021/11/03', toDate: '2021/11/17', } expect(globRoutes.fromDate).type.toBeString() expect(globRoutes.toDate).type.toBeString() }) test('Single Glob route params', () => { const globRoutes: RouteParams<'/from/{fromDate...}'> = { fromDate: '2021/11/03', } expect(globRoutes.fromDate).type.toBeString() }) test('Starts with Glob route params', () => { const globRoutes: RouteParams<'/{description...}-little/kittens'> = { description: 'cute', } expect(globRoutes.description).type.toBeString() }) context('Glob params in the middle', () => { test('Multiple Glob route params', () => { const middleGlob: RouteParams<'/repo/{folders...}/edit'> = { folders: 'src/lib/auth.js', } expect(middleGlob.folders).type.toBeString() }) }) test('Mixed typed and untyped params', () => { const untypedFirst: RouteParams<'/mixed/{b}/{c:Boolean}'> = { b: 'bazinga', c: true, } const typedFirst: RouteParams<'/mixed/{b:Float}/{c}'> = { b: 1245, c: 'stringy-string', } expect(untypedFirst.b).type.toBeString() expect(untypedFirst.c).type.toBeBoolean() expect(typedFirst.b).type.toBeNumber() expect(typedFirst.c).type.toBeString() }) test('Params in the middle', () => { const paramsInTheMiddle: RouteParams<'/posts/{authorId:string}/{id:Int}/edit'> = { authorId: 'id:author', id: 10, } expect(paramsInTheMiddle.authorId).type.toBeString() expect(paramsInTheMiddle.id).type.toBeNumber() }) }) describe('ParamType<>', () => { test('Float', () => { expect<ParamType<'Float'>>().type.toBeAssignable(1.02) }) test('Boolean', () => { expect<ParamType<'Boolean'>>().type.toBeAssignable(true) expect<ParamType<'Boolean'>>().type.toBeAssignable(false) }) test('Int', () => { expect<ParamType<'Int'>>().type.toBeAssignable(51) }) test('String', () => { expect<ParamType<'String'>>().type.toBeAssignable('bazinga') }) })
5,860
0
petrpan-code/redwoodjs/redwood/packages/structure/src/model
petrpan-code/redwoodjs/redwood/packages/structure/src/model/__tests__/model.test.ts
import { basename, resolve } from 'path' import { DefaultHost } from '../../hosts' import { URL_file } from '../../x/URL' import { RWProject } from '../RWProject' describe('Redwood Project Model', () => { it('can process example-todo-main', async () => { const projectRoot = getFixtureDir('example-todo-main') const project = new RWProject({ projectRoot, host: new DefaultHost() }) const pageNames = new Set(project.pages.map((p) => p.basenameNoExt)) expect(pageNames).toEqual( new Set([ 'FatalErrorPage', 'HomePage', 'NotFoundPage', 'PrivatePage', 'TypeScriptPage', 'EditUserPage', 'FooPage', 'BarPage', ]) ) for (const page of project.pages) { page.basenameNoExt page.route?.id } expect( project.sdls.map((s) => s.name).sort((a, b) => (a < b ? -1 : 1)) ).toEqual(['currentUser', 'todos']) for (const c of project.components) { c.basenameNoExt } project.components.length project.components.map((c) => c.basenameNoExt) project.functions.length project.services.length project.sdls.length const ds = await project.collectDiagnostics() ds.length const uri = URL_file(projectRoot, 'api/src/graphql/todos.sdl.js') const node = await project.findNode(uri) expect(node).toBeDefined() expect(node?.id).toEqual(uri) if (node) { const info = await node.collectIDEInfo() info.length info } }) it('example-todo-main-with-errors', async () => { const projectRoot = getFixtureDir('example-todo-main-with-errors') const project = new RWProject({ projectRoot, host: new DefaultHost() }) const ds = await project.collectDiagnostics() expect(ds.length).toBeGreaterThan(0) // const diagnosticCodes = new Set(ds.map((d) => d.diagnostic.code)) // expect(diagnosticCodes).toEqual( // new Set([RWError.NOTFOUND_PAGE_NOT_DEFINED]) // ) const dss = await project.router.collectDiagnostics() expect(dss.length).toBeGreaterThan(0) }) }) describe('Cells', () => { it('Correctly determines a Cell component vs a normal component', () => { const projectRoot = getFixtureDir('example-todo-main-with-errors') const project = new RWProject({ projectRoot, host: new DefaultHost() }) const cells = project.cells expect(cells).toHaveLength(1) expect(cells.map((cell) => basename(cell.filePath))).not.toContain( 'TableCell.js' ) }) it('Can get the operation name of the QUERY', () => { const projectRoot = getFixtureDir('example-todo-main') const project = new RWProject({ projectRoot, host: new DefaultHost() }) const cell = project.cells.find((x) => x.uri.endsWith('TodoListCell.tsx')) expect(cell?.queryOperationName).toMatch('TodoListCell_GetTodos') }) it('Warns you when you do not supply a name to QUERY', async () => { const projectRoot = getFixtureDir('example-todo-main-with-errors') const project = new RWProject({ projectRoot, host: new DefaultHost() }) const cell = project.cells.find((x) => x.uri.endsWith('TodoListCell.js')) const x = await cell?.collectDiagnostics() expect(x).not.toBeUndefined() expect(x?.map((e) => e.diagnostic.message)).toContain( 'We recommend that you name your query operation' ) }) }) describe.skip('env vars', () => { it('Warns if env vars are not ok', async () => { const projectRoot = getFixtureDir('example-todo-main-with-errors') const project = new RWProject({ projectRoot, host: new DefaultHost() }) project.envHelper.process_env_expressions.length const env = project.envHelper env.env env.env_defaults project.redwoodTOML.web_includeEnvironmentVariables env.process_env_expressions }) }) describe('Redwood Route detection', () => { it('detects routes with the prerender prop', async () => { const projectRoot = getFixtureDir('example-todo-main') const project = new RWProject({ projectRoot, host: new DefaultHost() }) const routes = project.getRouter().routes const prerenderRoutes = routes .filter((r) => r.prerender) // Make it a little easier to read by only keeping the attributes we're // interested in .map(({ name, path }) => ({ name, path })) expect(prerenderRoutes.length).toBe(6) expect(prerenderRoutes).toContainEqual({ name: 'home', path: '/' }) expect(prerenderRoutes).toContainEqual({ name: 'typescriptPage', path: '/typescript', }) expect(prerenderRoutes).toContainEqual({ name: 'someOtherPage', path: '/somewhereElse', }) expect(prerenderRoutes).toContainEqual({ name: 'fooPage', path: '/foo' }) expect(prerenderRoutes).toContainEqual({ name: 'barPage', path: '/bar' }) expect(prerenderRoutes).toContainEqual({ name: 'privatePage', path: '/private-page', }) }) }) function getFixtureDir( name: | 'example-todo-main-with-errors' | 'example-todo-main' | 'empty-project' | 'test-project' ) { return resolve(__dirname, `../../../../../__fixtures__/${name}`) }
5,863
0
petrpan-code/redwoodjs/redwood/packages/structure/src/model/util
petrpan-code/redwoodjs/redwood/packages/structure/src/model/util/__tests__/advanced_path_parser.test.ts
import { advanced_path_parser } from '../advanced_path_parser' describe('advanced_path_parser', () => { test('it works', () => { const route = '/foo/{param1}/bar/{baz:Int}/x' advanced_path_parser(route) //? }) })
5,864
0
petrpan-code/redwoodjs/redwood/packages/structure/src/model/util
petrpan-code/redwoodjs/redwood/packages/structure/src/model/util/__tests__/process_env_diagnostics.test.ts
import { resolve, join } from 'path' import { process_env_findInFile, process_env_findAll } from '../process_env' describe('process_env_findInFile', () => { test('can find process.env.FOO', () => { const code = ` function sayHello(){ console.log(process.env.FOO) } ` const r = process_env_findInFile('file1.ts', code) expect(r.length).toEqual(1) expect(r[0].key).toEqual('FOO') }) test('can find process.env["FOO"]', () => { const code = ` function sayHello(){ console.log(process.env["FOO"]) } ` const r = process_env_findInFile('file1.ts', code) expect(r.length).toEqual(1) expect(r[0].key).toEqual('FOO') }) test('can skip process.env expressions in comments/trivia/strings', () => { const code = ` function sayHello(){ const x = " process.env" // console.log(process.env["FOO"]) } ` const r = process_env_findInFile('file1.ts', code) expect(r.length).toEqual(0) }) test('process_env_findAll', async () => { const pp = getFixtureDir('example-todo-main-with-errors') //const webRoot = join(pp, 'web') const apiRoot = join(pp, 'api') const r = process_env_findAll(apiRoot) r //? }) }) function getFixtureDir( name: 'example-todo-main-with-errors' | 'example-todo-main' ) { return resolve(__dirname, `../../../../../../__fixtures__/${name}`) }
5,868
0
petrpan-code/redwoodjs/redwood/packages/structure/src/outline
petrpan-code/redwoodjs/redwood/packages/structure/src/outline/__tests__/outline.test.ts
import { resolve } from 'path' import { DefaultHost } from '../../hosts' import { RWProject } from '../../model' import { getOutline } from '../outline' import { outlineToJSON } from '../types' describe('Redwood Project Outline', () => { it('can be built for example-todo-main', async () => { const projectRoot = getFixtureDir('example-todo-main') const project = new RWProject({ projectRoot, host: new DefaultHost() }) const outline = getOutline(project) const outlineJSON = await outlineToJSON(outline) outlineJSON //? }) }) function getFixtureDir( name: 'example-todo-main-with-errors' | 'example-todo-main' ) { return resolve(__dirname, `../../../../../__fixtures__/${name}`) }
5,879
0
petrpan-code/redwoodjs/redwood/packages/structure/src/x
petrpan-code/redwoodjs/redwood/packages/structure/src/x/__tests__/URL.test.ts
import { sep } from 'path' import { URL_file, URL_toFile } from '../URL' describe('URL_fromFile', () => { it('works for windows style paths', async () => { expect(URL_file(`\\a\\b.c`)).toEqual('file:///a/b.c') expect(URL_file(`\\a\\b.c`)).toEqual('file:///a/b.c') expect(URL_file(`C:\\a`, `b.c`)).toEqual('file:///C:/a/b.c') }) it('works for linux style paths', async () => { expect(URL_file(`/a/b.c`)).toEqual('file:///a/b.c') expect(URL_file(`/a`, 'b.c')).toEqual('file:///a/b.c') }) it('works with file:// URLs', async () => { expect(URL_file('file:///a/b.c')).toEqual('file:///a/b.c') expect(URL_file(`file:///a`, 'b.c')).toEqual('file:///a/b.c') }) }) describe('URL_toFile', () => { it('works', async () => { const res = `${sep}a${sep}b.c` expect(URL_toFile(`/a/b.c`)).toEqual(res) expect(URL_toFile(`file:///a/b.c`)).toEqual(res) }) it('works with urlencoded windows file URLs (vscode language server does it this way)', () => { expect(URL_toFile(`file:///c%3A/a/b.c`, '\\')).toEqual('c:\\a\\b.c') }) })
5,880
0
petrpan-code/redwoodjs/redwood/packages/structure/src/x
petrpan-code/redwoodjs/redwood/packages/structure/src/x/__tests__/prisma.test.ts
import { Range } from 'vscode-languageserver' import { prisma_parseEnvExpressions } from '../prisma' describe('prisma_parseEnvExpressions', () => { it('can find env() expressions in a prisma schema', async () => { const [r] = Array.from(prisma_parseEnvExpressions(`env("foo") `)) const range = Range.create(0, 0, 0, 10) expect(r).toEqual({ range, key: 'foo' }) }) })
5,881
0
petrpan-code/redwoodjs/redwood/packages/structure/src/x
petrpan-code/redwoodjs/redwood/packages/structure/src/x/__tests__/vscode-languageserver-types-x.test.ts
import { DiagnosticSeverity, Position, Range, } from 'vscode-languageserver-types' import type { ExtendedDiagnostic } from '../vscode-languageserver-types' import { ExtendedDiagnostic_format, Position_compare, Position_fromOffset, Range_contains, } from '../vscode-languageserver-types' describe('Position_compare', () => { it('', async () => { x(0, 0, 0, 0, 'equal') x(0, 0, 0, 1, 'smaller') x(0, 0, 1, 0, 'smaller') x(0, 0, 1, 1, 'smaller') x(0, 1, 0, 0, 'greater') x(1, 0, 0, 0, 'greater') x(1, 1, 0, 0, 'greater') x(0, 2, 1, 0, 'smaller') function x(l1: number, c1: number, l2: number, c2: number, r: string) { expect( Position_compare(Position.create(l1, c1), Position.create(l2, c2)) ).toEqual(r) } }) }) describe('Range_contains', () => { it('', async () => { const r = Range.create(0, 1, 0, 3) x(r, 0, 0, false) x(r, 0, 1, true) x(r, 0, 2, true) x(r, 0, 3, true) x(r, 0, 4, false) function x(r: Range, l: number, c: number, res: boolean) { expect(Range_contains(r, Position.create(l, c))).toEqual(res) } }) }) describe('ExtendedDiagnostic_format', () => { it('can format diagnostics', async () => { const d: ExtendedDiagnostic = { uri: 'file:///path/to/app/b.ts', diagnostic: { range: Range.create(1, 2, 1, 6), severity: DiagnosticSeverity.Error, message: 'this is a message', }, } const str = ExtendedDiagnostic_format(d, { cwd: '/path/to/app/' }) expect(str).toEqual('b.ts:2:3: error: this is a message') const str2 = ExtendedDiagnostic_format(d) expect(str2).toEqual('/path/to/app/b.ts:2:3: error: this is a message') const str3 = ExtendedDiagnostic_format(d, { getSeverityLabel: (s) => `<${s}>`, }) expect(str3).toEqual('/path/to/app/b.ts:2:3: <1>: this is a message') }) }) describe('Position_fromOffset', () => { test('it works', () => { x(0, 'foo', 0, 0) x(1, 'foo', 0, 1) x(3, 'foo\nbar', 0, 3) x(4, 'foo\nbar', 1, 0) expect(Position_fromOffset(1000, 'foo')).toBeUndefined() function x( offset: number, text: string, expectedLine: number, expectedCharacter: number ) { const pos = Position_fromOffset(offset, text) pos //? expect(pos).toEqual({ line: expectedLine, character: expectedCharacter }) } }) })
6,019
0
petrpan-code/redwoodjs/redwood/packages/testing/src/api
petrpan-code/redwoodjs/redwood/packages/testing/src/api/__tests__/directUrlHelpers.test.ts
import fs from 'fs' import path from 'path' import { checkAndReplaceDirectUrl, getDefaultDb } from '../directUrlHelpers' const FIXTURE_DIR_PATH = path.resolve('..', '..', '__fixtures__') const NO_DIRECT_URL_FIXTURE_PATH = path.join(FIXTURE_DIR_PATH, 'test-project') const DIRECT_URL_FIXTURE_PATH = path.join(FIXTURE_DIR_PATH, 'empty-project') it("does nothing if directUrl isn't set", () => { process.env.RWJS_CWD = NO_DIRECT_URL_FIXTURE_PATH checkAndReplaceDirectUrl( fs.readFileSync( path.join(NO_DIRECT_URL_FIXTURE_PATH, 'api', 'db', 'schema.prisma'), 'utf-8' ), getDefaultDb(NO_DIRECT_URL_FIXTURE_PATH) ) expect(process.env.DIRECT_URL).toBeUndefined() delete process.env.RWJS_CWD }) it("overwrites directUrl if it's set", () => { process.env.RWJS_CWD = DIRECT_URL_FIXTURE_PATH const defaultDb = getDefaultDb(DIRECT_URL_FIXTURE_PATH) const directUrlEnvVar = checkAndReplaceDirectUrl( fs.readFileSync( path.join(DIRECT_URL_FIXTURE_PATH, 'api', 'db', 'schema.prisma'), 'utf-8' ), defaultDb ) expect(process.env[directUrlEnvVar as string]).toBe(defaultDb) delete process.env.RWJS_CWD }) it("overwrites directUrl if it's set and formatted", () => { const prismaSchema = `datasource db { provider = "sqlite" url = env("DATABASE_URL") directUrl = env("DIRECT_URL") shadowDatabaseUrl = env("SHADOW_DATABASE_URL") }` process.env.RWJS_CWD = DIRECT_URL_FIXTURE_PATH const defaultDb = getDefaultDb(DIRECT_URL_FIXTURE_PATH) const directUrlEnvVar = checkAndReplaceDirectUrl(prismaSchema, defaultDb) expect(process.env[directUrlEnvVar as string]).toBe(defaultDb) })
6,032
0
petrpan-code/redwoodjs/redwood/packages/testing/src/web
petrpan-code/redwoodjs/redwood/packages/testing/src/web/__tests__/MockHandlers.test.tsx
import 'whatwg-fetch' import React, { useCallback, useState } from 'react' import { render, screen, fireEvent, waitFor } from '@testing-library/react' import { mockGraphQLQuery } from '../mockRequests' jest.setTimeout(6_000) describe('GraphQLMockHandlers', () => { it('should allow you to compose mock graphql handlers for more complex tests', async () => { const baseResult = { article: { id: 1, title: 'Foobar', body: 'Lorem ipsum...', }, } const onceResult = { article: { id: 1, title: 'Foobar1', body: 'Lorem ipsum123...', }, } // Create the base response that always returns mockGraphQLQuery('GetArticle', () => baseResult) // Create a one time handler mockGraphQLQuery('GetArticle', () => onceResult, 'once') const FakeComponent = () => { const [result, setResult] = useState() const [fetching, setFetching] = useState(false) const doFetch = useCallback(() => { setFetching(true) fetch('https://example.com/graphql', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ query: ` query GetArticle($id: ID!) { article(id: $id) { id title body } } `, variables: { id: 1, }, }), }) .then(async (result) => { const data = await result.json() setResult(data) }) .catch((err) => { console.error('err', err) }) .finally(() => setFetching(false)) }, []) return ( <div> <button data-testid="fetch" onClick={doFetch}> Fetch </button> <div data-testid="result">{JSON.stringify(result)}</div> <div data-testid="status">{String(fetching)}</div> </div> ) } render(<FakeComponent />) const button = screen.getByTestId('fetch') const result = screen.getByTestId('result') const status = screen.getByTestId('status') fireEvent.click(button) await waitFor( () => expect(JSON.parse(result.textContent)).toEqual({ data: onceResult, }), { timeout: 2_000, } ) fireEvent.click(button) await waitFor( () => expect(JSON.parse(result.textContent)).toEqual({ data: baseResult, }), { timeout: 2_000, } ) fireEvent.click(button) await waitFor( () => { expect(status).toHaveTextContent('false') expect(JSON.parse(result.textContent)).toEqual({ data: baseResult, }) }, { timeout: 2_000, } ) }) })
6,033
0
petrpan-code/redwoodjs/redwood/packages/testing/src/web
petrpan-code/redwoodjs/redwood/packages/testing/src/web/__tests__/MockRouter.test.tsx
import React from 'react' import { render } from '@testing-library/react' import { Route, Private } from '@redwoodjs/router' import { routes, Router } from '../MockRouter' const FakePage = () => <></> describe('MockRouter', () => { it('should correctly map routes', () => { render( <Router> <Route name="a" path="/a" page={FakePage} /> <Route name="b" path="/b" page={FakePage} /> <Private unauthenticated="a"> <Route name="c" path="/c" page={FakePage} /> <Route name="d" path="/d" page={FakePage} /> </Private> </Router> ) expect(Object.keys(routes)).toEqual( expect.arrayContaining(['a', 'b', 'c', 'd']) ) }) })
6,034
0
petrpan-code/redwoodjs/redwood/packages/testing/src/web
petrpan-code/redwoodjs/redwood/packages/testing/src/web/__tests__/findCellMocks.test.ts
import path from 'path' import { ensurePosixPath } from '@redwoodjs/project-config' import { findCellMocks } from '../findCellMocks' const FIXTURE_PATH = path.resolve( __dirname, '../../../../../__fixtures__/example-todo-main' ) const cleanPaths = (p) => { return ensurePosixPath(path.relative(FIXTURE_PATH, p)) } test('Finds cell mocks from example-todo', () => { const mockPaths = findCellMocks(FIXTURE_PATH).map(cleanPaths) expect(mockPaths).toEqual([ 'web/src/components/NumTodosCell/NumTodosCell.mock.js', 'web/src/components/NumTodosTwoCell/NumTodosTwoCell.mock.js', 'web/src/components/TodoListCell/TodoListCell.mock.js', ]) })
6,146
0
petrpan-code/redwoodjs/redwood/packages/web/src
petrpan-code/redwoodjs/redwood/packages/web/src/__typetests__/cellProps.test.tsx
// These are normally auto-imported by babel import React from 'react' import gql from 'graphql-tag' import { describe, expect, test } from 'tstyche' import type { CellProps, CellSuccessProps } from '@redwoodjs/web' type ExampleQueryVariables = { category: string saved: boolean } // Just an example model returned from the query type Recipe = { __typename?: 'Recipe' id: string name: string } // This is the type returned by querying // e.g. query ListRecipes { recipes { id name } } type QueryResult = { __typename?: 'Query' recipes: Array<Recipe> } // This is how graphql-codegen defines queries that don't take vars type EmptyVariables = { [key: string]: never } // This Cell takes a customProp i.e. one not provided by the Cell's query interface SuccessProps extends CellSuccessProps<QueryResult> { customProp: number } const recipeCell = { QUERY: gql` query ListRecipes { recipes { id name } } `, Loading: () => null, Empty: () => null, Failure: () => null, Success: (props: SuccessProps) => { return ( <> <h1>Example Component</h1> <ul> <li>Recipe prop {props.recipes.length} </li> <li>Custom prop {props.customProp}</li> </ul> </> ) }, } describe('CellProps mapper type', () => { describe('when beforeQuery does not exist', () => { test('Inputs expect props outside cell', () => { type CellInputs = CellProps< typeof recipeCell.Success, QueryResult, typeof recipeCell, ExampleQueryVariables > expect<CellInputs>().type.toBeAssignable({ customProp: 55, category: 'Dinner', saved: true, }) }) test('Inputs still expect custom props when query does not take variables', () => { type CellWithoutVariablesInputs = CellProps< typeof recipeCell.Success, QueryResult, typeof recipeCell, EmptyVariables > expect<CellWithoutVariablesInputs>().type.toBeAssignable({ customProp: 55, }) }) }) describe('when beforeQuery exists and has arguments', () => { test('Inputs expect props outside cell', () => { const cellWithBeforeQuery = { ...recipeCell, beforeQuery: ({ word }: { word: string }) => { return { variables: { category: word, saved: !!word, }, } }, } type CellWithBeforeQueryInputs = CellProps< typeof cellWithBeforeQuery.Success, QueryResult, typeof cellWithBeforeQuery, ExampleQueryVariables > // Note that the gql variables are no longer required here expect<CellWithBeforeQueryInputs>().type.toBeAssignable({ word: 'abracadabra', customProp: 99, }) }) test('Inputs still expect custom props when query does not take variables', () => { const cellWithBeforeQuery = { ...recipeCell, beforeQuery: ({ fetchPolicy }: { fetchPolicy: string }) => { return { fetchPolicy, } }, } type CellWithBeforeQueryInputs = CellProps< typeof cellWithBeforeQuery.Success, QueryResult, typeof cellWithBeforeQuery, EmptyVariables > expect<CellWithBeforeQueryInputs>().type.toBeAssignable({ fetchPolicy: 'cache-only', customProp: 55, }) }) }) describe('when beforeQuery exists and has no arguments', () => { test('Inputs expect props outside cell', () => { const cellWithBeforeQuery = { ...recipeCell, beforeQuery: () => { return { variables: { category: 'Dinner', saved: true, }, } }, } type CellWithBeforeQueryInputs = CellProps< typeof cellWithBeforeQuery.Success, QueryResult, typeof cellWithBeforeQuery, ExampleQueryVariables > // Note that the gql variables are no longer required here expect<CellWithBeforeQueryInputs>().type.toBeAssignable({ customProp: 99, }) }) test('Inputs still expect custom props when query does not take variables', () => { const cellWithBeforeQuery = { ...recipeCell, beforeQuery: () => { return { fetchPolicy: 'cache-only', } }, } type CellWithBeforeQueryInputs = CellProps< typeof cellWithBeforeQuery.Success, QueryResult, typeof cellWithBeforeQuery, EmptyVariables > expect<CellWithBeforeQueryInputs>().type.toBeAssignable({ customProp: 55, }) }) }) })
6,147
0
petrpan-code/redwoodjs/redwood/packages/web/src
petrpan-code/redwoodjs/redwood/packages/web/src/__typetests__/cellSuccessData.test.tsx
import { describe, expect, it } from 'tstyche' import type { CellSuccessData } from '@redwoodjs/web' describe('CellSuccessData', () => { describe('when there is exactly one non-typename property', () => { it('omits __typename', () => { const value: CellSuccessData<{ foo: string; __typename: '' }> = { foo: '', } expect(value).type.toEqual<{ foo: string }>() }) it('removes null and undefined from properties', () => { const value: CellSuccessData<{ foo?: string | null }> = { foo: '' } expect(value).type.toEqual<{ foo: string }>() }) }) describe('when there are multiple non-typename properties', () => { it('omits __typename', () => { const value: CellSuccessData<{ foo: string bar: string __typename: '' }> = { foo: '', bar: '', } expect(value).type.toEqual<{ foo: string; bar: string }>() }) it('does not remove null or undefined from properties', () => { const value: CellSuccessData<{ foo?: string | null bar?: string | null }> = { foo: '', bar: '', } expect(value).type.toEqual<{ foo?: string | null; bar?: string | null }>() }) }) })
6,165
0
petrpan-code/redwoodjs/redwood/packages/web/src
petrpan-code/redwoodjs/redwood/packages/web/src/components/FetchConfigProvider.test.tsx
/** * @jest-environment jsdom */ import React from 'react' import { render, screen, waitFor } from '@testing-library/react' import type { AuthContextInterface } from '@redwoodjs/auth' import '@testing-library/jest-dom/extend-expect' globalThis.RWJS_API_GRAPHQL_URL = 'https://api.example.com/graphql' import { FetchConfigProvider, useFetchConfig } from './FetchConfigProvider' const FetchConfigToString: React.FunctionComponent = () => { const c = useFetchConfig() return <>{JSON.stringify(c)}</> } describe('FetchConfigProvider', () => { test('Unauthenticated user does not receive headers', () => { render( <FetchConfigProvider useAuth={() => ({ loading: false, isAuthenticated: false, } as AuthContextInterface< unknown, unknown, unknown, unknown, unknown, unknown, unknown, unknown >) } > <FetchConfigToString /> </FetchConfigProvider> ) expect( screen.getByText('{"uri":"https://api.example.com/graphql"}') ).toBeInTheDocument() }) test('Authenticated user does receive headers', async () => { render( <FetchConfigProvider useAuth={() => ({ loading: false, isAuthenticated: true, type: 'custom', } as AuthContextInterface< unknown, unknown, unknown, unknown, unknown, unknown, unknown, unknown >) } > <FetchConfigToString /> </FetchConfigProvider> ) await waitFor(() => screen.getByText( '{"uri":"https://api.example.com/graphql","headers":{"auth-provider":"custom"}}' ) ) }) })
6,167
0
petrpan-code/redwoodjs/redwood/packages/web/src
petrpan-code/redwoodjs/redwood/packages/web/src/components/GraphQLHooksProvider.test.tsx
/** * @jest-environment jsdom */ import { render, screen, waitFor } from '@testing-library/react' import '@testing-library/jest-dom/extend-expect' import { GraphQLHooksProvider, useQuery, useMutation, useSubscription, } from './GraphQLHooksProvider' const TestUseQueryHook: React.FunctionComponent = () => { // @ts-expect-error - Purposefully not passing in a DocumentNode type here. const result = useQuery('query TestQuery { answer }', { variables: { question: 'What is the answer to life, the universe and everything?', }, }) return <>{JSON.stringify(result)}</> } const TestUseMutationHook: React.FunctionComponent = () => { // @ts-expect-error - Purposefully not passing in a DocumentNode type here. const result = useMutation('mutation UpdateThing(input: "x") { answer }', { variables: { question: 'What is the answer to life, the universe and everything?', }, }) return <>{JSON.stringify(result)}</> } const TestUseSubscriptionHook: React.FunctionComponent = () => { // @ts-expect-error - Purposefully not passing in a DocumentNode type here. const result = useSubscription('subscription TestQuery { answer }', { variables: { question: 'What is the answer to life, the universe and everything?', }, }) return <>{JSON.stringify(result)}</> } describe('QueryHooksProvider', () => { test('useQueryHook is called with the correct query and arguments', (done) => { const myUseQueryHook = (query, options) => { expect(query).toEqual('query TestQuery { answer }') expect(options.variables.question).toEqual( 'What is the answer to life, the universe and everything?' ) done() return { loading: false, data: { answer: 42 } } } render( <GraphQLHooksProvider useQuery={myUseQueryHook} useMutation={null} useSubscription={null} > <TestUseQueryHook /> </GraphQLHooksProvider> ) }) test('useMutationHook is called with the correct query and arguments', (done) => { const myUseMutationHook = (query, options) => { expect(query).toEqual('mutation UpdateThing(input: "x") { answer }') expect(options.variables.question).toEqual( 'What is the answer to life, the universe and everything?' ) done() return { loading: false, data: { answer: 42 } } } render( <GraphQLHooksProvider useQuery={null} useMutation={myUseMutationHook} useSubscription={null} > <TestUseMutationHook /> </GraphQLHooksProvider> ) }) test('useQueryHook returns the correct result', async () => { const myUseQueryHook = () => { return { loading: false, data: { answer: 42 } } } render( <GraphQLHooksProvider useQuery={myUseQueryHook} useMutation={null}> <TestUseQueryHook /> </GraphQLHooksProvider> ) await waitFor(() => screen.getByText('{"loading":false,"data":{"answer":42}}') ) }) test('useMutationHook returns the correct result', async () => { const myUseMutationHook = () => { return { loading: false, data: { answer: 42 } } } render( <GraphQLHooksProvider useQuery={null} useMutation={myUseMutationHook}> <TestUseMutationHook /> </GraphQLHooksProvider> ) await waitFor(() => screen.getByText('{"loading":false,"data":{"answer":42}}') ) }) test('useSubscriptionHook returns the correct result', async () => { const myUseSubscriptionHook = () => { return { loading: false, data: { answer: 42 } } } render( <GraphQLHooksProvider useQuery={null} useMutation={null} useSubscription={myUseSubscriptionHook} > <TestUseSubscriptionHook /> </GraphQLHooksProvider> ) await waitFor(() => screen.getByText('{"loading":false,"data":{"answer":42}}') ) }) })
6,174
0
petrpan-code/redwoodjs/redwood/packages/web/src
petrpan-code/redwoodjs/redwood/packages/web/src/components/portalHead.test.tsx
import React from 'react' import '@testing-library/jest-dom/extend-expect' import { render } from '@testing-library/react' import PortalHead from './PortalHead' import * as ServerInject from './ServerInject' const serverInsertionHookSpy = jest .spyOn(ServerInject, 'useServerInsertedHTML') .mockImplementation(jest.fn()) describe('Portal head', () => { const TestUsage = () => { return ( <PortalHead> <title>Test title</title> <link rel="canonical" href="https://example.com" /> <meta name="description" content="Kittens are soft and cuddly" /> </PortalHead> ) } it('Should add children to the <head> on the client, and call serverInsertion hook', () => { render(<TestUsage />) // Actually doesn't do anything on the client underneath, but we // still want to make sure its called expect(serverInsertionHookSpy).toHaveBeenCalled() const head = document.querySelector('head') as HTMLHeadElement expect(head.childNodes).toHaveLength(3) expect(head.childNodes[0]).toHaveTextContent('Test title') expect(head.childNodes[1]).toHaveAttribute('rel', 'canonical') expect(head.childNodes[1]).toHaveAttribute('href', 'https://example.com') expect(head.childNodes[2]).toHaveAttribute('name', 'description') expect(head.childNodes[2]).toHaveAttribute( 'content', 'Kittens are soft and cuddly' ) }) })
6,178
0
petrpan-code/redwoodjs/redwood/packages/web/src/components
petrpan-code/redwoodjs/redwood/packages/web/src/components/cell/createCell.test.tsx
/** * @jest-environment jsdom */ import { render, screen } from '@testing-library/react' import '@testing-library/jest-dom/extend-expect' import { GraphQLHooksProvider } from '../GraphQLHooksProvider' import { createCell } from './createCell' describe('createCell', () => { beforeAll(() => { globalThis.RWJS_ENV = { RWJS_EXP_STREAMING_SSR: false, } }) test('Renders a static Success component', async () => { const TestCell = createCell({ // @ts-expect-error - Purposefully using a plain string here. QUERY: 'query TestQuery { answer }', Success: () => <>Great success!</>, }) const myUseQueryHook = () => ({ data: {} }) render( <GraphQLHooksProvider useQuery={myUseQueryHook} useMutation={null}> <TestCell /> </GraphQLHooksProvider> ) screen.getByText(/^Great success!$/) }) test('Renders Success with data', async () => { const TestCell = createCell({ // @ts-expect-error - Purposefully using a plain string here. QUERY: 'query TestQuery { answer }', Success: ({ answer }) => ( <> <dl> <dt>What&apos;s the meaning of life?</dt> <dd>{answer}</dd> </dl> </> ), }) const myUseQueryHook = () => { return { data: { answer: 42 } } } render( <GraphQLHooksProvider useQuery={myUseQueryHook} useMutation={null}> <TestCell /> </GraphQLHooksProvider> ) screen.getByText(/^What's the meaning of life\?$/) screen.getByText(/^42$/) }) test('Renders Success if any of the fields have data (i.e. not just the first)', async () => { const TestCell = createCell({ // @ts-expect-error - Purposefully using a plain string here. QUERY: 'query TestQuery { users { name } posts { title } }', Empty: () => <>No users or posts</>, Success: ({ users, posts }) => ( <> <div> {users.length > 0 ? ( <ul> {users.map(({ name }) => ( <li key={name}>{name}</li> ))} </ul> ) : ( 'no users' )} </div> <div> {posts.length > 0 ? ( <ul> {posts.map(({ title }) => ( <li key={title}>{title}</li> ))} </ul> ) : ( 'no posts' )} </div> </> ), }) const myUseQueryHook = () => { return { data: { users: [], posts: [{ title: 'bazinga' }, { title: 'kittens' }], }, } } render( <GraphQLHooksProvider useQuery={myUseQueryHook} useMutation={null}> <TestCell /> </GraphQLHooksProvider> ) screen.getByText(/bazinga/) screen.getByText(/kittens/) }) test('Renders default Loading when there is no data', async () => { const TestCell = createCell({ // @ts-expect-error - Purposefully using a plain string here. QUERY: 'query TestQuery { answer }', Success: () => <>Great success!</>, }) const myUseQueryHook = () => ({ loading: true }) render( <GraphQLHooksProvider useQuery={myUseQueryHook} useMutation={null}> <TestCell /> </GraphQLHooksProvider> ) screen.getByText(/^Loading...$/) }) test('Renders custom Loading when there is no data', async () => { const TestCell = createCell({ // @ts-expect-error - Purposefully using a plain string here. QUERY: 'query TestQuery { answer }', Success: () => <>Great success!</>, Loading: () => <>Fetching answer...</>, }) const myUseQueryHook = () => ({ loading: true }) render( <GraphQLHooksProvider useQuery={myUseQueryHook} useMutation={null}> <TestCell /> </GraphQLHooksProvider> ) screen.getByText(/^Fetching answer...$/) }) test('Renders Success even when `loading` is true if there is data', async () => { const TestCell = createCell({ // @ts-expect-error - Purposefully using a plain string here. QUERY: 'query TestQuery { answer }', Success: () => <>Great success!</>, Loading: () => <>Fetching answer...</>, }) const myUseQueryHook = () => ({ loading: true, data: {} }) render( <GraphQLHooksProvider useQuery={myUseQueryHook} useMutation={null}> <TestCell /> </GraphQLHooksProvider> ) screen.getByText(/^Great success!$/) }) test('Renders Empty if available, and data field is null', async () => { const TestCell = createCell({ // @ts-expect-error - Purposefully using a plain string here. QUERY: 'query TestQuery { answer }', Success: () => <>Great success!</>, Empty: () => <>No one knows</>, }) const myUseQueryHook = () => ({ loading: true, data: { answer: null } }) render( <GraphQLHooksProvider useQuery={myUseQueryHook} useMutation={null}> <TestCell /> </GraphQLHooksProvider> ) screen.getByText(/^No one knows$/) }) test('Renders Empty if available, and data field is an empty array', async () => { const TestCell = createCell({ // @ts-expect-error - Purposefully using a plain string here. QUERY: 'query TestQuery { answers }', Success: () => <>Great success!</>, Empty: () => <>No one knows</>, }) const myUseQueryHook = () => ({ loading: true, data: { answers: [] } }) render( <GraphQLHooksProvider useQuery={myUseQueryHook} useMutation={null}> <TestCell /> </GraphQLHooksProvider> ) screen.getByText(/^No one knows$/) }) test('Renders Success even if data is empty when no Empty is available', async () => { const TestCell = createCell({ // @ts-expect-error - Purposefully using a plain string here. QUERY: 'query TestQuery { answer }', Success: () => <>Empty success</>, }) const myUseQueryHook = () => ({ loading: true, data: { answer: null } }) render( <GraphQLHooksProvider useQuery={myUseQueryHook} useMutation={null}> <TestCell /> </GraphQLHooksProvider> ) screen.getByText(/^Empty success$/) }) test('Allows passing children to Success', async () => { const TestCell = createCell({ // @ts-expect-error - Purposefully using a plain string here. QUERY: 'query TestQuery { answer }', Success: ({ children }) => <>Look at my beautiful {children}</>, }) const myUseQueryHook = () => ({ data: {} }) render( <GraphQLHooksProvider useQuery={myUseQueryHook} useMutation={null}> <TestCell> <div>🦆</div> </TestCell> </GraphQLHooksProvider> ) screen.getByText(/^Look at my beautiful$/) screen.getByText(/^🦆$/) }) test('Cell props are passed to the query as variables', async () => { const TestCell = createCell({ // @ts-expect-error - Purposefully using a plain string here. QUERY: `query Greet($name: String!) { greet(name: $name) { greeting } }`, Success: ({ greeting }) => <p>{greeting}</p>, }) const myUseQueryHook = (_query: any, options: any) => { return { data: { greeting: `Hello ${options.variables.name}!` } } } render( <GraphQLHooksProvider useQuery={myUseQueryHook} useMutation={null}> <TestCell name="Bob" /> </GraphQLHooksProvider> ) screen.getByText(/^Hello Bob!$/) }) test('Allows QUERY to be a function', async () => { const TestCell = createCell({ // @ts-expect-error - Purposefully using a plain string here. QUERY: ({ variables }) => { if ((variables as any).character === 'BEAST') { return 'query BeastQuery { name }' } return 'query HeroQuery { name }' }, Success: ({ name }) => <p>Call me {name}</p>, }) const myUseQueryHook = (query: any) => { if (query.includes('BeastQuery')) { return { data: { name: 'Boogeyman' } } } else if (query.includes('HeroQuery')) { return { data: { name: 'Lara Croft' } } } return { data: { name: 'John Doe' } } } render( <GraphQLHooksProvider useQuery={myUseQueryHook} useMutation={null}> <TestCell character="BEAST" /> <TestCell character="HERO" /> </GraphQLHooksProvider> ) screen.getByText(/^Call me Boogeyman$/) screen.getByText(/^Call me Lara Croft$/) }) test('Renders Failure when there is an error', async () => { const TestCell = createCell({ // @ts-expect-error - Purposefully using a plain string here. QUERY: 'query TestQuery { answer }', Failure: () => <>Sad face :(</>, Success: () => <>Great success!</>, Loading: () => <>Fetching answer...</>, }) const myUseQueryHook = () => ({ error: true }) render( <GraphQLHooksProvider useQuery={myUseQueryHook} useMutation={null}> <TestCell /> </GraphQLHooksProvider> ) screen.getByText(/^Sad face :\($/) }) test('Passes error to Failure component', async () => { const TestCell = createCell({ // @ts-expect-error - Purposefully using a plain string here. QUERY: 'query TestQuery { answer }', Failure: ({ error }) => <>{JSON.stringify(error)}</>, Success: () => <>Great success!</>, Loading: () => <>Fetching answer...</>, }) const myUseQueryHook = () => ({ error: { msg: 'System malfunction' } }) render( <GraphQLHooksProvider useQuery={myUseQueryHook} useMutation={null}> <TestCell /> </GraphQLHooksProvider> ) screen.getByText(/^{"msg":"System malfunction"}$/) }) test('Passes error and errorCode to Failure component', async () => { const TestCell = createCell({ // @ts-expect-error - Purposefully using a plain string here. QUERY: 'query TestQuery { answer }', Failure: ({ error, errorCode }) => ( <> {JSON.stringify(error)},code:{errorCode} </> ), Success: () => <>Great success!</>, Loading: () => <>Fetching answer...</>, }) const myUseQueryHook = () => ({ error: { msg: 'System malfunction' }, errorCode: 'SIMON_SAYS_NO', }) render( <GraphQLHooksProvider useQuery={myUseQueryHook} useMutation={null}> <TestCell /> </GraphQLHooksProvider> ) screen.getByText(/^{"msg":"System malfunction"},code:SIMON_SAYS_NO$/) }) test('Passes children to Failure', async () => { const TestCell = createCell({ // @ts-expect-error - Purposefully using a plain string here. QUERY: 'query TestQuery { answer }', Failure: ({ children }) => <>I&apos;m a failure {children}</>, }) const myUseQueryHook = () => ({ error: {} }) render( <GraphQLHooksProvider useQuery={myUseQueryHook} useMutation={null}> <TestCell> <div>Child</div> </TestCell> </GraphQLHooksProvider> ) screen.getByText(/^I'm a failure$/) screen.getByText(/^Child$/) }) test('Throws an error when there is an error if no Failure component exists', async () => { const TestCell = createCell({ // @ts-expect-error - Purposefully using a plain string here. QUERY: 'query TestQuery { answer }', Success: () => <>Great success!</>, Loading: () => <>Fetching answer...</>, }) const myUseQueryHook = () => ({ error: { message: '200 GraphQL' } }) // Prevent writing to stderr during this render. const err = console.error console.error = jest.fn() let error try { render( <GraphQLHooksProvider useQuery={myUseQueryHook} useMutation={null}> <TestCell /> </GraphQLHooksProvider> ) } catch (e) { error = e } expect(error.message).toEqual('200 GraphQL') // Restore writing to stderr. console.error = err }) test('Allows overriding of default isDataEmpty', async () => { const TestCell = createCell({ // @ts-expect-error - Purposefully using a plain string here. QUERY: 'query TestQuery { answer }', Success: () => <>Great success!</>, Empty: () => <>Got nothing</>, isEmpty: () => true, }) const myUseQueryHook = () => ({ data: {}, loading: false, }) render( <GraphQLHooksProvider useQuery={myUseQueryHook} useMutation={null}> <TestCell /> </GraphQLHooksProvider> ) screen.getByText(/^Got nothing$/) }) test('Allows mixing isDataEmpty with custom logic', async () => { const TestCell = createCell({ // @ts-expect-error - Purposefully using a plain string here. QUERY: 'query TestQuery { answer }', Success: () => <>Great success!</>, Empty: () => <>Got nothing</>, isEmpty: (data, { isDataEmpty }) => isDataEmpty(data) || data.answer === '0', }) const myUseQueryHook = () => ({ data: { answer: '0' }, loading: false, }) render( <GraphQLHooksProvider useQuery={myUseQueryHook} useMutation={null}> <TestCell /> </GraphQLHooksProvider> ) screen.getByText(/^Got nothing$/) }) test('Allows overriding variables in beforeQuery', async () => { const TestCell = createCell({ // @ts-expect-error - Purposefully using a plain string here. QUERY: `query Greet($name: String!) { greet(name: $name) { greeting } }`, Success: ({ greeting }) => <p>{greeting}</p>, beforeQuery: () => ({ variables: { name: 'Bob', }, }), }) const myUseQueryHook = (_query: any, options: any) => { return { data: { greeting: `Hello ${options.variables.name}!` } } } render( <GraphQLHooksProvider useQuery={myUseQueryHook} useMutation={null}> <TestCell /> </GraphQLHooksProvider> ) screen.getByText(/^Hello Bob!$/) }) })
6,180
0
petrpan-code/redwoodjs/redwood/packages/web/src/components
petrpan-code/redwoodjs/redwood/packages/web/src/components/cell/createSuspendingCell.test.tsx
/** * @jest-environment jsdom */ import type { useReadQuery, useBackgroundQuery } from '@apollo/client' import { loadErrorMessages, loadDevMessages } from '@apollo/client/dev' import { render, screen } from '@testing-library/react' import '@testing-library/jest-dom/extend-expect' import { GraphQLHooksProvider } from '../GraphQLHooksProvider' import { createSuspendingCell } from './createSuspendingCell' type ReadQueryHook = typeof useReadQuery type BgQueryHook = typeof useBackgroundQuery jest.mock('@apollo/client', () => { return { useApolloClient: jest.fn(), } }) // @TODO: once we have finalised implementation, we need to add tests for // all the other states. We would also need to figure out how to test the Suspense state. // No point doing this now, as the implementation is in flux! describe('createSuspendingCell', () => { beforeAll(() => { globalThis.RWJS_ENV = { RWJS_EXP_STREAMING_SSR: true, } loadDevMessages() loadErrorMessages() }) const mockedUseBgQuery = (() => { return ['mocked-query-ref', { refetch: jest.fn(), fetchMore: jest.fn() }] }) as unknown as BgQueryHook const mockedQueryHook = () => ({ data: {} }) test.only('Renders a static Success component', async () => { const TestCell = createSuspendingCell({ // @ts-expect-error - Purposefully using a plain string here. QUERY: 'query TestQuery { answer }', Success: () => <>Great success!</>, }) render( <GraphQLHooksProvider useBackgroundQuery={mockedUseBgQuery as any} useReadQuery={mockedQueryHook as any} > <TestCell /> </GraphQLHooksProvider> ) screen.getByText(/^Great success!$/) }) test.only('Renders Success with data', async () => { const TestCell = createSuspendingCell({ // @ts-expect-error - Purposefully using a plain string here. QUERY: 'query TestQuery { answer }', Success: ({ answer }) => ( <> <dl> <dt>What&apos;s the meaning of life?</dt> <dd>{answer}</dd> </dl> </> ), }) const myUseQueryHook = (() => { return { data: { answer: 42 } } }) as unknown as ReadQueryHook render( <GraphQLHooksProvider useReadQuery={myUseQueryHook} useBackgroundQuery={mockedUseBgQuery} > <TestCell /> </GraphQLHooksProvider> ) screen.getByText(/^What's the meaning of life\?$/) screen.getByText(/^42$/) }) test.only('Renders Success if any of the fields have data (i.e. not just the first)', async () => { const TestCell = createSuspendingCell({ // @ts-expect-error - Purposefully using a plain string here. QUERY: 'query TestQuery { users { name } posts { title } }', Empty: () => <>No users or posts</>, Success: ({ users, posts }) => ( <> <div> {users.length > 0 ? ( <ul> {users.map(({ name }) => ( <li key={name}>{name}</li> ))} </ul> ) : ( 'no users' )} </div> <div> {posts.length > 0 ? ( <ul> {posts.map(({ title }) => ( <li key={title}>{title}</li> ))} </ul> ) : ( 'no posts' )} </div> </> ), }) const myReadQueryHook = (() => { return { data: { users: [], posts: [{ title: 'bazinga' }, { title: 'kittens' }], }, } }) as unknown as ReadQueryHook render( <GraphQLHooksProvider useReadQuery={myReadQueryHook} useBackgroundQuery={mockedUseBgQuery} > <TestCell /> </GraphQLHooksProvider> ) screen.getByText(/bazinga/) screen.getByText(/kittens/) }) })
6,275
0
petrpan-code/redwoodjs/redwood/tasks
petrpan-code/redwoodjs/redwood/tasks/server-tests/server.test.ts
const fs = require('fs') const http = require('http') const path = require('path') const execa = require('execa') // Set up RWJS_CWD. let original_RWJS_CWD beforeAll(() => { original_RWJS_CWD = process.env.RWJS_CWD process.env.RWJS_CWD = path.join(__dirname, './fixtures/redwood-app') }) afterAll(() => { process.env.RWJS_CWD = original_RWJS_CWD }) // Clean up the child process after each test. let child afterEach(async () => { if (!child) { return } child.cancel() // Wait for child process to terminate. try { await child } catch (e) { // Ignore the error. } }) const TIMEOUT = 1_000 * 2 const commandStrings = { '@redwoodjs/cli': `node ${path.resolve( __dirname, '../../packages/cli/dist/index.js' )} serve`, '@redwoodjs/api-server': `node ${path.resolve( __dirname, '../../packages/api-server/dist/index.js' )}`, '@redwoodjs/web-server': `node ${path.resolve( __dirname, '../../packages/web-server/dist/server.js' )}`, } const redwoodToml = fs.readFileSync( path.join(__dirname, './fixtures/redwood-app/redwood.toml'), 'utf-8' ) const { groups: { apiUrl }, } = redwoodToml.match(/apiUrl = "(?<apiUrl>[^"]*)/) describe.each([ [`${commandStrings['@redwoodjs/cli']}`], [`${commandStrings['@redwoodjs/api-server']}`], ])('serve both (%s)', (commandString) => { it('serves both sides, using the apiRootPath in redwood.toml', async () => { child = execa.command(commandString) await new Promise((r) => setTimeout(r, TIMEOUT)) const webRes = await fetch('http://localhost:8910/about') const webBody = await webRes.text() expect(webRes.status).toEqual(200) expect(webBody).toEqual( fs.readFileSync( path.join(__dirname, './fixtures/redwood-app/web/dist/about.html'), 'utf-8' ) ) const apiRes = await fetch(`http://localhost:8910${apiUrl}/hello`) const apiBody = await apiRes.json() expect(apiRes.status).toEqual(200) expect(apiBody).toEqual({ data: 'hello function' }) }) it('--port changes the port', async () => { const port = 8920 child = execa.command(`${commandString} --port ${port}`) await new Promise((r) => setTimeout(r, TIMEOUT)) const webRes = await fetch(`http://localhost:${port}/about`) const webBody = await webRes.text() expect(webRes.status).toEqual(200) expect(webBody).toEqual( fs.readFileSync( path.join(__dirname, './fixtures/redwood-app/web/dist/about.html'), 'utf-8' ) ) const apiRes = await fetch(`http://localhost:${port}${apiUrl}/hello`) const apiBody = await apiRes.json() expect(apiRes.status).toEqual(200) expect(apiBody).toEqual({ data: 'hello function' }) }) }) describe.each([ [`${commandStrings['@redwoodjs/cli']} api`], [`${commandStrings['@redwoodjs/api-server']} api`], ])('serve api (%s)', (commandString) => { it('serves the api side', async () => { child = execa.command(commandString) await new Promise((r) => setTimeout(r, TIMEOUT)) const res = await fetch('http://localhost:8911/hello') const body = await res.json() expect(res.status).toEqual(200) expect(body).toEqual({ data: 'hello function' }) }) it('--port changes the port', async () => { const port = 3000 child = execa.command(`${commandString} --port ${port}`) await new Promise((r) => setTimeout(r, TIMEOUT)) const res = await fetch(`http://localhost:${port}/hello`) const body = await res.json() expect(res.status).toEqual(200) expect(body).toEqual({ data: 'hello function' }) }) it('--apiRootPath changes the prefix', async () => { const apiRootPath = '/api' child = execa.command(`${commandString} --apiRootPath ${apiRootPath}`) await new Promise((r) => setTimeout(r, TIMEOUT)) const res = await fetch(`http://localhost:8911${apiRootPath}/hello`) const body = await res.json() expect(res.status).toEqual(200) expect(body).toEqual({ data: 'hello function' }) }) }) // We can't test @redwoodjs/cli here because it depends on node_modules. describe.each([ [`${commandStrings['@redwoodjs/api-server']} web`], [commandStrings['@redwoodjs/web-server']], ])('serve web (%s)', (commandString) => { it('serves the web side', async () => { child = execa.command(commandString) await new Promise((r) => setTimeout(r, TIMEOUT)) const res = await fetch('http://localhost:8910/about') const body = await res.text() expect(res.status).toEqual(200) expect(body).toEqual( fs.readFileSync( path.join(__dirname, './fixtures/redwood-app/web/dist/about.html'), 'utf-8' ) ) }) it('--port changes the port', async () => { const port = 8912 child = execa.command(`${commandString} --port ${port}`) await new Promise((r) => setTimeout(r, TIMEOUT)) const res = await fetch(`http://localhost:${port}/about`) const body = await res.text() expect(res.status).toEqual(200) expect(body).toEqual( fs.readFileSync( path.join(__dirname, './fixtures/redwood-app/web/dist/about.html'), 'utf-8' ) ) }) it('--apiHost changes the upstream api url', async () => { const apiPort = 8916 const apiHost = 'localhost' const helloData = { data: 'hello from mock server' } const server = http.createServer((req, res) => { if (req.url === '/hello') { res.end(JSON.stringify(helloData)) } }) server.listen(apiPort, apiHost) child = execa.command( `${commandString} --apiHost http://${apiHost}:${apiPort}` ) await new Promise((r) => setTimeout(r, TIMEOUT)) const res = await fetch('http://localhost:8910/.redwood/functions/hello') const body = await res.json() expect(res.status).toEqual(200) expect(body).toEqual(helloData) server.close() }) it("doesn't error out on unknown args", async () => { child = execa.command(`${commandString} --foo --bar --baz`) await new Promise((r) => setTimeout(r, TIMEOUT)) const res = await fetch('http://localhost:8910/about') const body = await res.text() expect(res.status).toEqual(200) expect(body).toEqual( fs.readFileSync( path.join(__dirname, './fixtures/redwood-app/web/dist/about.html'), 'utf-8' ) ) }) }) describe('@redwoodjs/cli', () => { describe('both server CLI', () => { const commandString = commandStrings['@redwoodjs/cli'] it.todo('handles --socket differently') it('has help configured', () => { const { stdout } = execa.commandSync(`${commandString} --help`) expect(stdout).toMatchInlineSnapshot(` "usage: rw <side> Commands: rw serve Run both api and web servers [default] rw serve api Start server for serving only the api rw serve web Start server for serving only the web side Options: --help Show help [boolean] --version Show version number [boolean] --cwd Working directory to use (where \`redwood.toml\` is located) --telemetry Whether to send anonymous usage telemetry to RedwoodJS [boolean] -p, --port [number] [default: 8910] --socket [string] Also see the Redwood CLI Reference (​https://redwoodjs.com/docs/cli-commands#serve​)" `) }) it('errors out on unknown args', async () => { const { stdout } = execa.commandSync(`${commandString} --foo --bar --baz`) expect(stdout).toMatchInlineSnapshot(` "usage: rw <side> Commands: rw serve Run both api and web servers [default] rw serve api Start server for serving only the api rw serve web Start server for serving only the web side Options: --help Show help [boolean] --version Show version number [boolean] --cwd Working directory to use (where \`redwood.toml\` is located) --telemetry Whether to send anonymous usage telemetry to RedwoodJS [boolean] -p, --port [number] [default: 8910] --socket [string] Also see the Redwood CLI Reference (​https://redwoodjs.com/docs/cli-commands#serve​) Unknown arguments: foo, bar, baz" `) }) }) describe('api server CLI', () => { const commandString = `${commandStrings['@redwoodjs/cli']} api` it.todo('handles --socket differently') it('loads dotenv files', async () => { child = execa.command(`${commandString}`) await new Promise((r) => setTimeout(r, TIMEOUT)) const res = await fetch(`http://localhost:8911/env`) const body = await res.json() expect(res.status).toEqual(200) expect(body).toEqual({ data: '42' }) }) it('has help configured', () => { const { stdout } = execa.commandSync(`${commandString} --help`) expect(stdout).toMatchInlineSnapshot(` "rw serve api Start server for serving only the api Options: --help Show help [boolean] --version Show version number [boolean] --cwd Working directory to use (where \`redwood.toml\` is located) --telemetry Whether to send anonymous usage telemetry to RedwoodJS [boolean] -p, --port [number] [default: 8911] --socket [string] --apiRootPath, --api-root-path, Root path where your api functions --rootPath, --root-path are served [string] [default: "/"]" `) }) it('errors out on unknown args', async () => { const { stdout } = execa.commandSync(`${commandString} --foo --bar --baz`) expect(stdout).toMatchInlineSnapshot(` "rw serve api Start server for serving only the api Options: --help Show help [boolean] --version Show version number [boolean] --cwd Working directory to use (where \`redwood.toml\` is located) --telemetry Whether to send anonymous usage telemetry to RedwoodJS [boolean] -p, --port [number] [default: 8911] --socket [string] --apiRootPath, --api-root-path, Root path where your api functions --rootPath, --root-path are served [string] [default: "/"] Unknown arguments: foo, bar, baz" `) }) }) describe('web server CLI', () => { const commandString = `${commandStrings['@redwoodjs/cli']} web` it.todo('handles --socket differently') it('has help configured', () => { const { stdout } = execa.commandSync(`${commandString} --help`) expect(stdout).toMatchInlineSnapshot(` "rw serve web Start server for serving only the web side Options: --help Show help [boolean] --version Show version number [boolean] --cwd Working directory to use (where \`redwood.toml\` is located) --telemetry Whether to send anonymous usage telemetry to RedwoodJS [boolean] -p, --port [number] [default: 8910] --socket [string] --apiHost, --api-host Forward requests from the apiUrl, defined in redwood.toml to this host [string]" `) }) it('errors out on unknown args', async () => { const { stdout } = execa.commandSync(`${commandString} --foo --bar --baz`) expect(stdout).toMatchInlineSnapshot(` "rw serve web Start server for serving only the web side Options: --help Show help [boolean] --version Show version number [boolean] --cwd Working directory to use (where \`redwood.toml\` is located) --telemetry Whether to send anonymous usage telemetry to RedwoodJS [boolean] -p, --port [number] [default: 8910] --socket [string] --apiHost, --api-host Forward requests from the apiUrl, defined in redwood.toml to this host [string] Unknown arguments: foo, bar, baz" `) }) }) }) describe('@redwoodjs/api-server', () => { describe('both server CLI', () => { const commandString = commandStrings['@redwoodjs/api-server'] it('--socket changes the port', async () => { const socket = 8921 child = execa.command(`${commandString} --socket ${socket}`) await new Promise((r) => setTimeout(r, TIMEOUT)) const webRes = await fetch(`http://localhost:${socket}/about`) const webBody = await webRes.text() expect(webRes.status).toEqual(200) expect(webBody).toEqual( fs.readFileSync( path.join(__dirname, './fixtures/redwood-app/web/dist/about.html'), 'utf-8' ) ) const apiRes = await fetch( `http://localhost:${socket}/.redwood/functions/hello` ) const apiBody = await apiRes.json() expect(apiRes.status).toEqual(200) expect(apiBody).toEqual({ data: 'hello function' }) }) it('--socket wins out over --port', async () => { const socket = 8922 const port = 8923 child = execa.command( `${commandString} --socket ${socket} --port ${port}` ) await new Promise((r) => setTimeout(r, TIMEOUT)) const webRes = await fetch(`http://localhost:${socket}/about`) const webBody = await webRes.text() expect(webRes.status).toEqual(200) expect(webBody).toEqual( fs.readFileSync( path.join(__dirname, './fixtures/redwood-app/web/dist/about.html'), 'utf-8' ) ) const apiRes = await fetch( `http://localhost:${socket}/.redwood/functions/hello` ) const apiBody = await apiRes.json() expect(apiRes.status).toEqual(200) expect(apiBody).toEqual({ data: 'hello function' }) }) it("doesn't have help configured", () => { const { stdout } = execa.commandSync(`${commandString} --help`) expect(stdout).toMatchInlineSnapshot(` "Options: --help Show help [boolean] --version Show version number [boolean]" `) }) it("doesn't error out on unknown args", async () => { child = execa.command(`${commandString} --foo --bar --baz`) await new Promise((r) => setTimeout(r, TIMEOUT)) const webRes = await fetch('http://localhost:8910/about') const webBody = await webRes.text() expect(webRes.status).toEqual(200) expect(webBody).toEqual( fs.readFileSync( path.join(__dirname, './fixtures/redwood-app/web/dist/about.html'), 'utf-8' ) ) const apiRes = await fetch( 'http://localhost:8910/.redwood/functions/hello' ) const apiBody = await apiRes.json() expect(apiRes.status).toEqual(200) expect(apiBody).toEqual({ data: 'hello function' }) }) }) describe('api server CLI', () => { const commandString = `${commandStrings['@redwoodjs/api-server']} api` it('--socket changes the port', async () => { const socket = 3001 child = execa.command(`${commandString} --socket ${socket}`) await new Promise((r) => setTimeout(r, TIMEOUT)) const res = await fetch(`http://localhost:${socket}/hello`) const body = await res.json() expect(res.status).toEqual(200) expect(body).toEqual({ data: 'hello function' }) }) it('--socket wins out over --port', async () => { const socket = 3002 const port = 3003 child = execa.command( `${commandString} --socket ${socket} --port ${port}` ) await new Promise((r) => setTimeout(r, TIMEOUT)) const res = await fetch(`http://localhost:${socket}/hello`) const body = await res.json() expect(res.status).toEqual(200) expect(body).toEqual({ data: 'hello function' }) }) it('--loadEnvFiles loads dotenv files', async () => { child = execa.command(`${commandString} --loadEnvFiles`) await new Promise((r) => setTimeout(r, TIMEOUT)) const res = await fetch(`http://localhost:8911/env`) const body = await res.json() expect(res.status).toEqual(200) expect(body).toEqual({ data: '42' }) }) it("doesn't have help configured", () => { const { stdout } = execa.commandSync(`${commandString} --help`) expect(stdout).toMatchInlineSnapshot(` "Options: --help Show help [boolean] --version Show version number [boolean]" `) }) it("doesn't error out on unknown args", async () => { child = execa.command(`${commandString} --foo --bar --baz`) await new Promise((r) => setTimeout(r, TIMEOUT)) const res = await fetch('http://localhost:8911/hello') const body = await res.json() expect(res.status).toEqual(200) expect(body).toEqual({ data: 'hello function' }) }) }) describe('web server CLI', () => { const commandString = `${commandStrings['@redwoodjs/api-server']} web` it('--socket changes the port', async () => { const socket = 8913 child = execa.command(`${commandString} --socket ${socket}`) await new Promise((r) => setTimeout(r, TIMEOUT)) const res = await fetch(`http://localhost:${socket}/about`) const body = await res.text() expect(res.status).toEqual(200) expect(body).toEqual( fs.readFileSync( path.join(__dirname, './fixtures/redwood-app/web/dist/about.html'), 'utf-8' ) ) }) it('--socket wins out over --port', async () => { const socket = 8914 const port = 8915 child = execa.command( `${commandString} --socket ${socket} --port ${port}` ) await new Promise((r) => setTimeout(r, TIMEOUT)) const res = await fetch(`http://localhost:${socket}/about`) const body = await res.text() expect(res.status).toEqual(200) expect(body).toEqual( fs.readFileSync( path.join(__dirname, './fixtures/redwood-app/web/dist/about.html'), 'utf-8' ) ) }) it("doesn't have help configured", () => { const { stdout } = execa.commandSync(`${commandString} --help`) expect(stdout).toMatchInlineSnapshot(` "Options: --help Show help [boolean] --version Show version number [boolean]" `) }) it("doesn't error out on unknown args", async () => { child = execa.command(`${commandString} --foo --bar --baz`, { stdio: 'inherit', }) await new Promise((r) => setTimeout(r, TIMEOUT)) const res = await fetch('http://localhost:8910/about') const body = await res.text() expect(res.status).toEqual(200) expect(body).toEqual( fs.readFileSync( path.join(__dirname, './fixtures/redwood-app/web/dist/about.html'), 'utf-8' ) ) }) }) }) describe('@redwoodjs/web-server', () => { const commandString = commandStrings['@redwoodjs/web-server'] it.todo('handles --socket differently') // @redwoodjs/web-server doesn't have help configured in a different way than the others. // The others output help, it's just empty. This doesn't even do that. It just runs. it("doesn't have help configured", async () => { child = execa.command(`${commandString} --help`) await new Promise((r) => setTimeout(r, TIMEOUT)) const res = await fetch('http://localhost:8910/about') const body = await res.text() expect(res.status).toEqual(200) expect(body).toEqual( fs.readFileSync( path.join(__dirname, './fixtures/redwood-app/web/dist/about.html'), 'utf-8' ) ) }) })
6,364
0
petrpan-code/redwoodjs/redwood/tasks/test-project/templates
petrpan-code/redwoodjs/redwood/tasks/test-project/templates/api/context.test.ts.template
test('Set a mock user on the context', async () => { const user = { id: 0o7, name: 'Bond, James Bond', email: '[email protected]', roles: 'secret_agent', } mockCurrentUser(user) expect(context.currentUser).toStrictEqual(user) }) test('Context is isolated between tests', () => { expect(context).toStrictEqual({ currentUser: undefined }) })
6,464
0
petrpan-code/microsoft/fluentui/apps
petrpan-code/microsoft/fluentui/apps/perf-test/tsconfig.json
{ "extends": "../../tsconfig.base.v8.json", "compilerOptions": { "target": "es5", "outDir": "lib", "module": "commonjs", "jsx": "react", "experimentalDecorators": true, "preserveConstEnums": true, "lib": ["ES2015", "DOM"], "types": ["webpack-env", "node"] }, "include": ["src"] }
7,390
0
petrpan-code/microsoft/fluentui/apps/react-18-tests-v8/src/components
petrpan-code/microsoft/fluentui/apps/react-18-tests-v8/src/components/ContextualMenu/ContextualMenuExample.test.tsx
import * as React from 'react'; import { render } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { ContextualMenuExample } from './ContextualMenuExample'; describe('ContextualMenu in React 18', () => { // eslint-disable-next-line @typescript-eslint/no-empty-function const noop = () => {}; beforeEach(() => { jest.spyOn(console, 'warn').mockImplementation(noop); }); it('should render ContextualMenu when trigger button is clicked', () => { const { getByRole, queryAllByRole } = render( <React.StrictMode> <ContextualMenuExample /> </React.StrictMode>, ); expect(queryAllByRole('menu').length).toBe(0); const menuTrigger = getByRole('button'); userEvent.click(menuTrigger); expect(queryAllByRole('menu').length).toBe(1); }); });
7,408
0
petrpan-code/microsoft/fluentui/apps/react-18-tests-v9
petrpan-code/microsoft/fluentui/apps/react-18-tests-v9/src/App.test.tsx
import { resetIdsForTests } from '@fluentui/react-utilities'; import { render } from '@testing-library/react'; import * as React from 'react'; import { App } from './App'; describe('App with React 18', () => { // eslint-disable-next-line @typescript-eslint/no-empty-function const noop = () => {}; beforeEach(() => { jest.spyOn(console, 'warn').mockImplementation(noop); }); afterEach(() => { resetIdsForTests(); }); describe('FluentProvider', () => { it('should apply matching className in strict mode', () => { const { getByText } = render( <React.StrictMode> <App /> </React.StrictMode>, ); const element = getByText('Click Me'); const elementProviderClassName = element.className.split(' ')[1]; const matchingStyleTag = document.getElementById(elementProviderClassName); expect(matchingStyleTag).toBeDefined; }); }); });
7,466
0
petrpan-code/microsoft/fluentui/apps
petrpan-code/microsoft/fluentui/apps/stress-test/tsconfig.json
{ "extends": "../../tsconfig.base.json", "compilerOptions": { "noEmit": false, "allowJs": true, "checkJs": true, "importHelpers": true, "isolatedModules": true, "jsx": "react", "noUnusedLocals": true, "preserveConstEnums": true, "experimentalDecorators": true, "types": ["environment"], "outDir": "./dist" }, "include": ["src"], "exclude": ["node_modules", "src/fixtures"] }
7,467
0
petrpan-code/microsoft/fluentui/apps
petrpan-code/microsoft/fluentui/apps/stress-test/tsconfig.scripts.json
{ "extends": "../../tsconfig.base.json", "compilerOptions": { "noEmit": false, "allowJs": true, "checkJs": true, "importHelpers": true, "isolatedModules": false, "jsx": "react", "noUnusedLocals": true, "preserveConstEnums": true, "experimentalDecorators": true, "types": ["environment", "node"], "moduleResolution": "node", "module": "ESNext", "esModuleInterop": true }, "include": ["src", "scripts"], "exclude": ["node_modules"] }
7,468
0
petrpan-code/microsoft/fluentui/apps
petrpan-code/microsoft/fluentui/apps/stress-test/tsconfig.type.json
{ "extends": "./tsconfig.json", "compilerOptions": { "noEmit": true, "moduleResolution": "node", "module": "ESNext", "esModuleInterop": true }, "include": ["src", "scenarios", "webpack", "scripts"] }
7,713
0
petrpan-code/microsoft/fluentui/apps/vr-tests-react-components/src
petrpan-code/microsoft/fluentui/apps/vr-tests-react-components/src/utilities/utilities.test.tsx
import * as React from 'react'; import { getStoryVariant, DARK_MODE, HIGH_CONTRAST, RTL } from './getStoryVariant'; import { Button } from '@fluentui/react-button'; import { ComponentStory } from '@storybook/react'; describe('utility functions', () => { describe('getStoryVariant', () => { const DefaultStory = () => <Button> Hello World</Button>; it('should set the correct direction for story', () => { const ltrStory = getStoryVariant(DefaultStory, DARK_MODE); const rtlStory = getStoryVariant(DefaultStory, RTL); expect(ltrStory.parameters.dir).toBe('ltr'); expect(rtlStory.parameters.dir).toBe('rtl'); }); it('should set the correct theme for story', () => { const darkModeStory = getStoryVariant(DefaultStory, DARK_MODE); const highContrastStory = getStoryVariant(DefaultStory, HIGH_CONTRAST); expect(darkModeStory.parameters.fluentTheme).toBe('web-dark'); expect(highContrastStory.parameters.fluentTheme).toBe('teams-high-contrast'); }); it('should set the correct name for story', () => { const darkModeStory = getStoryVariant(DefaultStory, DARK_MODE); const highContrastStory = getStoryVariant(DefaultStory, HIGH_CONTRAST); const rtlStory = getStoryVariant(DefaultStory, RTL); expect(darkModeStory.storyName).toEqual('Default Story - Dark Mode'); expect(highContrastStory.storyName).toEqual('Default Story - High Contrast'); expect(rtlStory.storyName).toEqual('Default Story - RTL'); const buttonStory: ComponentStory<any> = DefaultStory; buttonStory.storyName = 'button'; const buttonDarkModeStory = getStoryVariant(buttonStory, DARK_MODE); const buttonHighContrastStory = getStoryVariant(buttonStory, HIGH_CONTRAST); const buttonRtlStory = getStoryVariant(buttonStory, RTL); expect(buttonDarkModeStory.storyName).toEqual('button - Dark Mode'); expect(buttonHighContrastStory.storyName).toEqual('button - High Contrast'); expect(buttonRtlStory.storyName).toEqual('button - RTL'); }); }); });
7,962
0
petrpan-code/microsoft/fluentui/packages/codemods/src/codeMods/tests
petrpan-code/microsoft/fluentui/packages/codemods/src/codeMods/tests/componentToCompat/componentToCompat.test.ts
import { Project } from 'ts-morph'; import * as Root from '../mock/compat/mockIndex'; import { RawCompat, runComponentToCompat, getNamedExports, buildCompatHash as buildHash, repathNamedImports, repathPathedImports, } from '../../mods/componentToCompat/compatHelpers'; const createComponentToCompat = (compat: RawCompat) => { return { oldPath: './mockIndex', newComponentPath: 'compat/Button', namedExports: getNamedExports(compat.namedExports), }; }; describe('Component to compat', () => { let project: Project; beforeEach(() => { project = new Project(); project.addSourceFilesAtPaths(`${process.cwd()}/**/tests/mock/compat/*.tsx`); }); it('correctly repaths from exact known import', () => { const file = project.getSourceFileOrThrow('ImportsStuff.tsx'); const hash = buildHash([{ componentName: 'Button', namedExports: Object.keys(Root) }], createComponentToCompat); repathPathedImports(file, hash.exactPathMatch); const imps = file.getImportDeclarations(); expect(imps.some(dec => dec.getModuleSpecifierValue() === 'compat/Button')).toEqual(true); }); it('correctly repaths from index', () => { const file = project.getSourceFileOrThrow('ImportsStuff.tsx'); const hash = buildHash([{ componentName: 'Button', namedExports: Object.keys(Root) }], createComponentToCompat); repathNamedImports(file, hash.namedExportsMatch, './DefaultButton'); const repathed = file.getImportDeclaration(d => d.getModuleSpecifierValue() === 'compat/Button'); expect(repathed).toBeTruthy(); }); it("correctly repaths and leaves named imports that don't match", () => { const file = project.getSourceFileOrThrow('ImportsStuff.tsx'); const hash = buildHash([{ componentName: 'Button', namedExports: ['Button'] }], createComponentToCompat); repathNamedImports(file, hash.namedExportsMatch, './Button'); const repathed = file.getImportDeclaration(d => d.getModuleSpecifierValue() === 'compat/Button'); expect(repathed).toBeTruthy(); const oldImport = file.getImportDeclaration(d => d.getModuleSpecifierValue() === './Button'); expect(oldImport).toBeTruthy(); const named = oldImport?.getNamedImports(); expect(named?.length).toEqual(1); expect(named![0].getName()).toEqual('OtherButton'); }); it('correctly moves all named imports from index', () => { const file = project.getSourceFileOrThrow('ImportsStuff.tsx'); const hash = buildHash([{ componentName: 'Button', namedExports: Object.keys(Root) }], createComponentToCompat); repathNamedImports(file, hash.namedExportsMatch, './Button'); const named = file.getImportDeclaration(d => d.getModuleSpecifierValue() === 'compat/Button')?.getNamedImports(); named?.forEach(v => { expect(v.getName() === 'Button' || v.getName() === 'OtherButton').toEqual(true); }); expect(named?.some(v => !!v.getAliasNode())).toEqual(true); }); it('correctly moves all named imports and all other imports', () => { const file = project.getSourceFileOrThrow('ImportsStuff.tsx'); const hash = buildHash([{ componentName: 'Button', namedExports: Object.keys(Root) }], createComponentToCompat); runComponentToCompat(file, hash, './DefaultButton'); const named = file.getImportDeclaration(d => d.getModuleSpecifierValue() === 'compat/Button')?.getNamedImports(); named?.forEach(v => { expect(v.getName() === 'Button' || v.getName() === 'DefaultButton').toEqual(true); }); }); it('correctly removes index if no imports left', () => { const file = project.getSourceFileOrThrow('ImportsStuff.tsx'); const hash = buildHash([{ componentName: 'Button', namedExports: Object.keys(Root) }], createComponentToCompat); repathNamedImports(file, hash.namedExportsMatch, './DefaultButton'); expect(file.getFullText()).not.toContain('./DefaultButton'); }); it('correctly builds a hash map', () => { const hash = buildHash([{ componentName: 'Button', namedExports: Object.keys(Root) }], createComponentToCompat); expect(hash.exactPathMatch['./mockIndex']).toEqual('compat/Button'); expect(hash.namedExportsMatch.DefaultButton).toEqual('compat/Button'); }); });
7,963
0
petrpan-code/microsoft/fluentui/packages/codemods/src/codeMods/tests
petrpan-code/microsoft/fluentui/packages/codemods/src/codeMods/tests/configMod/configMod.test.ts
import { Project } from 'ts-morph'; import { runMods } from '../../../modRunner/runnerUtilities'; import { CodeMod } from '../../types'; /* This is a TEST file for developers to try out their config-based codemods. */ //const DropdownPropsFile = 'mDropdownProps.tsx'; describe('Tests a simple data-driven codeMod', () => { let project: Project; /* Before you test, add the desired source file to your project! */ beforeEach(() => { project = new Project(); project.addSourceFilesAtPaths(`${process.cwd()}/**/tests/mock/**/*.tsx`); }); it('can run all mods in upgrades.json successfully', () => { /* Run and test your codemod here! */ const codemodArray: CodeMod[] = []; // TODO: Add your own codemod array! runMods( codemodArray, project.getSourceFiles(), () => null, result => { result.result.resolve( v => { console.log(`Upgraded file ${result.file.getBaseName()} with mod ${result.mod.name}`, v.logs); }, e => { console.warn( `Mod ${result.mod.name} did not run on file ${result.file.getBaseName()} for: `, 'error' in e ? e.error : e.logs, ); }, ); }, ); }); });
7,985
0
petrpan-code/microsoft/fluentui/packages/codemods/src/codeMods/tests
petrpan-code/microsoft/fluentui/packages/codemods/src/codeMods/tests/officeToFluentImport/officeToFluentImport.test.ts
import { Project, SourceFile } from 'ts-morph'; import RepathOfficeToFluentImports from '../../mods/officeToFluentImport/officeToFluentImport.mod'; const basicFileName = 'mockImports.tsx'; const edgeCaseFile = 'mockEdgeImports.tsx'; const newRoot = '@fluentui/react'; const oldRoot = 'office-ui-fabric-react'; const oldFabricRoot = '@uifabric'; const newFluentRoot = '@fluentui'; describe('Office to Fluent import repath tests', () => { const project: Project = new Project(); project.addSourceFilesAtPaths(`${process.cwd()}/**/tests/mock/utils/*.tsx`); let file: SourceFile; afterEach(() => { file.refreshFromFileSystemSync(); }); it('Can remove all old paths in one file', () => { file = project.getSourceFileOrThrow(basicFileName); RepathOfficeToFluentImports.run(file); file.getImportStringLiterals().forEach(val => { const impPath = val.getLiteralValue(); expect(impPath.indexOf(oldRoot)).not.toEqual(0); }); }); it('Can replace all old paths in one with the new root', () => { file = project.getSourceFileOrThrow(basicFileName); const oldImportList = file.getImportStringLiterals().map(val => { return val.getLiteralValue(); }); RepathOfficeToFluentImports.run(file); const newImpList = file.getImportStringLiterals(); expect(newImpList.some(val => val.getLiteralValue().indexOf(newRoot) > -1)).toBe(true); newImpList.forEach((val, index) => { if (oldImportList[index] === oldRoot) { expect(val.getLiteralValue().indexOf(newRoot)).toBe(0); } }); }); it('Only Replaces paths that start with oufr', () => { file = project.getSourceFileOrThrow(edgeCaseFile); const oldImportList = file.getImportStringLiterals().map(val => { return val.getLiteralValue(); }); RepathOfficeToFluentImports.run(file); const newImpList = file.getImportStringLiterals(); newImpList.forEach((val, index) => { const indexOfOld: number = oldImportList[index].indexOf(oldRoot); if (indexOfOld === 0) { expect(val.getLiteralValue().indexOf(newRoot)).toBe(0); // If the old index didn't start the path, then we should ensure // That this import hasn't changed } else if (indexOfOld > 0) { expect(val.getLiteralValue()).toEqual(oldImportList[index]); } }); }); it('Can replace all old paths in one with the new root', () => { file = project.getSourceFileOrThrow(basicFileName); const oldImportList = file.getImportStringLiterals().map(val => { return val.getLiteralValue(); }); RepathOfficeToFluentImports.run(file); const newImpList = file.getImportStringLiterals(); expect(newImpList.some(val => val.getLiteralValue().indexOf(newRoot) > -1)).toBe(true); newImpList.forEach((val, index) => { if (oldImportList[index].indexOf(oldRoot) === 0) { expect(val.getLiteralValue().indexOf(newRoot)).toBe(0); } }); }); it('Replaces @uifabric with @fluentui', () => { file = project.getSourceFileOrThrow(basicFileName); const oldImportList = file.getImportStringLiterals().map(val => { return val.getLiteralValue(); }); RepathOfficeToFluentImports.run(file); const newImpList = file.getImportStringLiterals(); expect(newImpList.some(val => val.getLiteralValue().indexOf(newFluentRoot) > -1)).toBe(true); newImpList.forEach((val, index) => { if (oldImportList[index].indexOf(oldFabricRoot) === 0) { expect(val.getLiteralValue().indexOf(newFluentRoot)).toBe(0); } }); }); it('Replaces old uifabric package to new package', () => { file = project.getSourceFileOrThrow(basicFileName); RepathOfficeToFluentImports.run(file); const newImpList = file.getImportStringLiterals(); expect(newImpList.some(val => val.getLiteralValue().indexOf('font-icons-mdl2') > -1)).toBe(true); }); });
7,986
0
petrpan-code/microsoft/fluentui/packages/codemods/src/codeMods/tests
petrpan-code/microsoft/fluentui/packages/codemods/src/codeMods/tests/oldToNewButton/oldToNewButton.test.ts
import { Project } from 'ts-morph'; import { findJsxTag, renameProp } from '../../utilities'; const buttonPath = '/**/tests/mock/**/button/**/*.tsx'; const dropDownPath = '/**/tests/mock/**/dropdown/**/*.tsx'; describe('Persona props mod tests', () => { let project: Project; beforeEach(() => { project = new Project(); project.addSourceFilesAtPaths(`${process.cwd()}${buttonPath}`); project.addSourceFilesAtPaths(`${process.cwd()}${dropDownPath}`); }); it('can work on the dropdown example', () => { const file = project.getSourceFileOrThrow('mDropdownSpreadProps.tsx'); const tags = findJsxTag(file, 'Dropdown'); renameProp(tags, 'isDisabled', 'disabled'); tags.forEach(val => { expect(val.getText().includes('disabled={isDisabled}')).toBeTruthy(); }); }); it('can rename a prop in a spread operator with complex spread examples', () => { const file = project.getSourceFileOrThrow('mCompoundButtonProps.tsx'); const tags = findJsxTag(file, 'CompoundButton'); renameProp(tags, 'toggled', 'checked', undefined, undefined); tags.forEach(val => { expect(val.getText().includes('checked={toggled}')).toBeTruthy(); }); }); });
7,987
0
petrpan-code/microsoft/fluentui/packages/codemods/src/codeMods/tests
petrpan-code/microsoft/fluentui/packages/codemods/src/codeMods/tests/personaToAvatar/componentMod.test.ts
import { Project, SyntaxKind, InterfaceDeclaration, TypeReferenceNode, PropertyAccessExpression } from 'ts-morph'; import { replacePersonaImport, replaceIPersonaPropsImport, replacePersonaSizeImport, } from '../../mods/personaToAvatar/personaToAvatar.mod'; import { findJsxTag } from '../../utilities'; const personaPath = '/**/tests/mock/**/persona/**/*.tsx'; describe('Persona component mod', () => { let project: Project; beforeEach(() => { project = new Project(); project.addSourceFilesAtPaths(`${process.cwd()}${personaPath}`); }); it('can replace persona with avatar', () => { const file = project.getSourceFileOrThrow('mFunction.tsx'); replacePersonaImport(file); file.getImportDeclarations().forEach(imp => { imp.getNamedImports().forEach(name => { expect(name.getText()).not.toEqual('Persona'); }); expect(findJsxTag(file, 'Persona').length).toBe(0); }); }); it('can replace IPersonaProps with AvatarProps', () => { const file = project.getSourceFileOrThrow('mInterface.tsx'); replaceIPersonaPropsImport(file); file.getImportDeclarations().forEach(imp => { imp.getNamedImports().forEach(name => { expect(name.getText()).not.toEqual('IPersonaProps'); }); file.forEachDescendant(val => { switch (val.getKind()) { case SyntaxKind.InterfaceDeclaration: { const tVal = val as InterfaceDeclaration; const struct = tVal.getStructure(); expect( (struct.extends as string[])?.some(str => { return str === 'IPersonaProps'; }), ).toBe(false); break; } case SyntaxKind.TypeReference: { expect((val as TypeReferenceNode).getText()).not.toEqual('IPersonaProps'); } } }); }); }); it('can replace PersonaSize with AvatarSize', () => { const file = project.getSourceFileOrThrow('mWithPersonaSize.tsx'); replacePersonaSizeImport(file); file.forEachDescendant(val => { // I believe that these are really the only two cases that a reference to PersonaSize // can be used. If we find others, there are other case statements that should be added switch (val.getKind()) { case SyntaxKind.TypeReference: { const tdesc = val as TypeReferenceNode; expect(tdesc.getText()).not.toEqual('PersonaSize'); break; } case SyntaxKind.PropertyAccessExpression: { const tdesc = val as PropertyAccessExpression; expect(tdesc.getFirstChild()?.getText()).not.toEqual('PersonaSize'); break; } } }); }); });
7,988
0
petrpan-code/microsoft/fluentui/packages/codemods/src/codeMods/tests
petrpan-code/microsoft/fluentui/packages/codemods/src/codeMods/tests/personaToAvatar/propsMod.test.ts
import { Project, SyntaxKind, JsxAttributeStructure } from 'ts-morph'; import { renamePrimaryTextProp, renameRenderCoin } from '../../mods/personaToAvatar/personaToAvatar.mod'; import { findJsxTag } from '../../utilities'; const personaPath = '/**/tests/mock/**/persona/**/*.tsx'; // @TODO ensure that props are not renamed for non fabric personas if they exist const personaPropsFile = 'mPersonaProps.tsx'; const personaSpreadPropsFile = 'mPersonaSpreadProps.tsx'; describe('Persona props mod tests', () => { let project: Project; beforeEach(() => { project = new Project(); project.addSourceFilesAtPaths(`${process.cwd()}${personaPath}`); }); it('can replace jsx inline primaryText prop', () => { const file = project.getSourceFileOrThrow('mPersonaProps.tsx'); renamePrimaryTextProp(file); const elements = findJsxTag(file, 'Persona'); elements.forEach(val => { expect(val.getAttribute('primaryText')).not.toBeTruthy(); }); }); it('can replace jsx inline primaryText without changing the value', () => { const file = project.getSourceFileOrThrow(personaPropsFile); const values = findJsxTag(file, 'Persona'); const attValues = values.map(val => { return (val.getAttribute('primaryText')?.getStructure() as JsxAttributeStructure)?.initializer; }); renamePrimaryTextProp(file); const elements = findJsxTag(file, 'Persona'); elements.forEach((val, index) => { expect((val.getAttribute('text')?.getStructure() as JsxAttributeStructure)?.initializer).toEqual( attValues[index], ); }); }); it('can replace jsx spread primaryText', () => { const file = project.getSourceFileOrThrow(personaSpreadPropsFile); renamePrimaryTextProp(file); const els = findJsxTag(file, 'Persona'); els.forEach(val => { val.getAttributes().forEach(att => { if (att.getKind() === SyntaxKind.JsxSpreadAttribute) { // This is really the best way to figure out if the spread property is expected to have the prop // that we care about. This won't catch all cases but for testing it's a good place to start. att .getFirstChildByKind(SyntaxKind.Identifier) ?.getType() .getProperties() .forEach(prop => { expect(prop.getName()).not.toEqual('primaryText'); }); } }); }); }); it('can replace personaCoin render', () => { const file = project.getSourceFileOrThrow(personaPropsFile); renameRenderCoin(file); const els = findJsxTag(file, 'Persona'); els.forEach(val => { expect(val.getAttribute('onRenderCoin')).toBeFalsy(); }); }); });
7,989
0
petrpan-code/microsoft/fluentui/packages/codemods/src/codeMods/tests
petrpan-code/microsoft/fluentui/packages/codemods/src/codeMods/tests/utilities/importUtils.test.ts
import { getImportsByPath, repathImport } from '../../utilities'; import { Err, Ok } from '../../../helpers/result'; import { Project, ImportDeclaration } from 'ts-morph'; import { NoOp } from '../../types'; const fileName = 'mockImports.tsx'; const rootPath = 'office-ui-fabric-react'; const buttonPath = `${rootPath}/lib/Button`; describe('Import Utilities test', () => { let project: Project; beforeEach(() => { project = new Project(); project.addSourceFilesAtPaths(`${process.cwd()}/**/tests/mock/utils/*.tsx`); }); it('can find import based on exact string match', () => { const file = project.getSourceFileOrThrow(fileName); const tag = getImportsByPath(file, buttonPath) .then(v => v[0].getModuleSpecifierValue()) .okOrElse('Error'); expect(tag).toEqual(buttonPath); }); it('only finds exact matches', () => { const file = project.getSourceFileOrThrow(fileName); const imp = getImportsByPath(file, rootPath) .then(v => v.length) .okOrElse(-1); expect(imp).toEqual(0); }); it('can find a single import based on a regex string match', () => { const file = project.getSourceFileOrThrow(fileName); const imp = getImportsByPath(file, /office\-ui\-fabric\-react.+Button/) .chain(v => { if (v.length !== 1) { return Err<ImportDeclaration, NoOp>({ logs: ['wrong number of results'] }); } return Ok(v[0]); }) .resolve( v => v.getModuleSpecifierValue(), () => 'error', ); expect(imp).toEqual(buttonPath); }); it('can find all imports based on a regex string match', () => { const file = project.getSourceFileOrThrow(fileName); const imps = getImportsByPath(file, /office\-ui\-fabric\-react/) .chain(v => { return v.length > 1 ? Ok(v) : Err<ImportDeclaration[], NoOp>({ logs: ['too few values returned'] }); }) .then(v => v.map(i => i.getModuleSpecifierValue())) .resolveOk(() => ['error']); imps.forEach(imp => { expect(imp).toContain(rootPath); }); }); it('can replace an import path', () => { const replacementString = 'Complete/NewPath'; const file = project.getSourceFileOrThrow(fileName); getImportsByPath(file, /office\-ui\-fabric\-react/) .then(v => v[0]) .then(v => repathImport(v, replacementString)); expect( file.getImportStringLiterals().some(val => { return val.getLiteralValue() === replacementString; }), ).toBe(true); }); it('can replace a partial import path', () => { const replacementRegex = /office\-ui\-fabric\-react/; const file = project.getSourceFileOrThrow(fileName); getImportsByPath(file, /office\-ui\-fabric\-react/) .then(v => v.shift()!) .then(v => repathImport(v, 'NewPath', replacementRegex)); expect( file.getImportStringLiterals().some(val => { return val.getLiteralValue() === 'NewPath/lib/Button'; }), ).toBe(true); }); });
7,990
0
petrpan-code/microsoft/fluentui/packages/codemods/src/codeMods/tests
petrpan-code/microsoft/fluentui/packages/codemods/src/codeMods/tests/utilities/jsxUtilities.test.ts
import { findJsxTag, renameImport } from '../../utilities'; import { Project } from 'ts-morph'; const project = new Project(); project.addSourceFilesAtPaths(`${process.cwd()}/**/tests/mock/**/*.tsx`); const fileName = 'mockFunction.tsx'; describe('JSX Utilities Test', () => { it('can find a regular jsx tag', () => { const tag = findJsxTag(project.getSourceFileOrThrow(fileName), 'JSXFunctionalNormalTag'); expect(tag.length).toEqual(1); }); it('can find a self closing jsx tag', () => { const tag = findJsxTag(project.getSourceFileOrThrow(fileName), 'JSXFunctionalSelfClosingTag'); expect(tag.length).toEqual(1); }); it('can replace a tag', () => { const file = project.getSourceFileOrThrow(fileName); renameImport(file, 'ToImport', 'Renamed'); expect(file.getText().indexOf('ToImport')).toBe(-1); }); });
7,991
0
petrpan-code/microsoft/fluentui/packages/codemods/src/codeMods/tests
petrpan-code/microsoft/fluentui/packages/codemods/src/codeMods/tests/utilities/propUtilities.test.ts
import { renameProp, findJsxTag, boolTransform, enumTransform, numberTransform } from '../../utilities'; import { Project, SyntaxKind, JsxAttribute } from 'ts-morph'; import { ValueMap, PropTransform } from '../../types'; import { Maybe } from '../../../helpers/maybe'; // const personaSpreadPropsFile = 'mPersonaSpreadProps.tsx'; const spinnerPropsFile = 'mSpinnerProps.tsx'; const spinnerSpreadPropsFile = 'mSpinnerSpreadProps.tsx'; const DropdownPropsFile = 'mDropdownProps.tsx'; const DropdownSpreadPropsFile = 'mDropdownSpreadProps.tsx'; /* Developer will provide a mapping of Enum Values, if necessary. */ // TODO it's not ideal that devs need to write the enum name before every token. const spinnerMap: ValueMap<string> = { 'SpinnerType.normal': 'SpinnerSize.medium', 'SpinnerType.large': 'SpinnerSize.large', }; describe('Props Utilities Test', () => { let project: Project; beforeEach(() => { project = new Project(); project.addSourceFilesAtPaths(`${process.cwd()}/**/tests/mock/**/*.tsx`); }); describe('Normal Prop Renaming', () => { it('[SANITY] can handle a no-op case', () => { const file = project.getSourceFileOrThrow(DropdownPropsFile); const tags = findJsxTag(file, 'Dropdown'); renameProp(tags, 'cannot find this tag!', 'nor this one!'); tags.forEach(tag => { expect(tag.getText()).not.toMatch('cannot find this tag!'); expect(tag.getText()).not.toMatch('nor this one!'); }); }); it('[SANITY] can handle a no-op case in the spread case', () => { const file = project.getSourceFileOrThrow(DropdownSpreadPropsFile); const tags = findJsxTag(file, 'Dropdown'); renameProp(tags, 'cannot find this tag!', 'nor this one!'); tags.forEach(tag => { expect(tag.getText()).not.toMatch('cannot find this tag!'); expect(tag.getText()).not.toMatch('nor this one!'); }); }); // TODO: investigate this worked before and fails now // it('can rename props in a spread attribute', () => { // const file = project.getSourceFileOrThrow(personaSpreadPropsFile); // const tags = findJsxTag(file, 'Persona'); // renameProp(tags, 'primaryText', 'Text', undefined); // tags.forEach(val => { // console.log(val.getAttribute('id')?.getText()); // expect(val.getText()).toMatch('Text={primaryText}'); // }); // }); describe('Edge Case Tests (changes in value)', () => { it('[SANITY] can ID the correct file and get the JSX elements', () => { const file = project.getSourceFileOrThrow(DropdownPropsFile); const tags = findJsxTag(file, 'Dropdown'); expect(tags.length).toEqual(2); }); it('can rename and replace the values of props (primitives)', () => { const file = project.getSourceFileOrThrow(DropdownPropsFile); const tags = findJsxTag(file, 'Dropdown'); renameProp(tags, 'isDisabled', 'disabled', 'false'); tags.forEach(tag => { expect(tag.getAttribute('isDisabled')).toBeFalsy(); const valMaybe = Maybe(tag.getAttribute('disabled')); const val = valMaybe.then(value => value.getFirstChildByKind(SyntaxKind.JsxExpression)); expect(val.something).toBeTruthy(); const propValueText = val.then(value => value.getText().substring(1, value.getText().length - 1)); expect(propValueText.something).toBeTruthy(); if (propValueText.something) { expect(propValueText.value).toEqual('false'); } }); }); it('can replace props with changed values in a spread attribute', () => { const file = project.getSourceFileOrThrow(DropdownSpreadPropsFile); const tags = findJsxTag(file, 'Dropdown'); renameProp(tags, 'isDisabled', 'disabled', 'false'); tags.forEach(val => { expect(val.getText()).toMatch('disabled={false}'); }); }); describe('Edge Case Tests (transform functions)', () => { it('can replace only the values of a given prop (number)', () => { const file = project.getSourceFileOrThrow(DropdownPropsFile); const tags = findJsxTag(file, 'Dropdown'); const func = numberTransform(100); renameProp(tags, 'dropdownWidth', 'dropdownWidth', undefined, func); tags.forEach(tag => { expect(tag.getAttribute('dropdownWidth')).toBeTruthy(); const valMaybe = Maybe(tag.getAttribute('dropdownWidth')); const val = valMaybe.then(value => value.getFirstChildByKind(SyntaxKind.JsxExpression)); expect(val.something).toBeTruthy(); const propValueText = val.then(value => value.getText().substring(1, value.getText().length - 1)); expect(propValueText.something).toBeTruthy(); if (propValueText.something) { expect(propValueText.value).toEqual('100'); } }); }); it('can rename and replace the values of props with a default value', () => { const file = project.getSourceFileOrThrow(DropdownPropsFile); const tags = findJsxTag(file, 'Dropdown'); const func = boolTransform(); // No args => assign to old value. renameProp(tags, 'isDisabled', 'disabled', undefined, func); tags.forEach(tag => { expect(tag.getAttribute('isDisabled')).toBeFalsy(); }); }); it('can replace props with changed enum values in Spinner (spread)', () => { const file = project.getSourceFileOrThrow(spinnerPropsFile); const tags = findJsxTag(file, 'Spinner'); const oldEnumValues: string[] = ['SpinnerType.large', 'SpinnerType.normal']; const enumFn = enumTransform(spinnerMap); renameProp(tags, 'type', 'size', undefined, enumFn); tags.forEach(tag => { expect(tag.getAttribute('type')).toBeFalsy(); const currentEnumValue = Maybe(oldEnumValues.pop()); const innerMaybe = Maybe( (tag.getAttribute('size') as JsxAttribute).getFirstChildByKind(SyntaxKind.JsxExpression), ); if (innerMaybe.something && currentEnumValue.something) { const inner = innerMaybe.then(value => { return value.getFirstChildByKind(SyntaxKind.PropertyAccessExpression); }); expect(inner.something).toBeTruthy(); expect(currentEnumValue.something).toBeTruthy(); const newVal = spinnerMap[currentEnumValue.value]; const firstInnerChild = inner.then(value => value.getFirstChildByKind(SyntaxKind.Identifier)); const LastInnerChild = inner.then(value => value.getLastChildByKind(SyntaxKind.Identifier)); expect(firstInnerChild.something).toBeTruthy(); expect(LastInnerChild.something).toBeTruthy(); if (firstInnerChild.something && LastInnerChild.something) { /* Need this if statement to clear value on the next line. */ expect(firstInnerChild.value.getText()).toEqual('SpinnerSize'); expect(LastInnerChild.value.getText()).toEqual(newVal.substring(newVal.indexOf('.') + 1)); } } }); }); it('can replace props with changed values in Dropdown (spread)', () => { const file = project.getSourceFileOrThrow(DropdownSpreadPropsFile); const tags = findJsxTag(file, 'Dropdown'); const transform: PropTransform = boolTransform(true, undefined); renameProp(tags, 'isDisabled', 'disabled', undefined, transform); tags.forEach(val => { expect(val.getText()).toMatch('disabled={true}'); }); }); it('can replace props with changed enum values in a spread attribute where the body is missing', () => { const file = project.getSourceFileOrThrow(spinnerSpreadPropsFile); let tags = findJsxTag(file, 'Spinner'); const transform = enumTransform(spinnerMap); renameProp(tags, 'type', 'size', undefined, transform); tags = findJsxTag(file, 'Spinner'); /* Need to reacquire tags because the tags have been modified since then! */ tags.forEach(val => { expect(val.getText()).toMatch('size={__migEnumMap[type]}'); }); }); }); it('can replace props with changed enum values in a spread attribute where the body is missing', () => { const file = project.getSourceFileOrThrow(spinnerSpreadPropsFile); let tags = findJsxTag(file, 'Spinner'); const transform = enumTransform(spinnerMap); renameProp(tags, 'type', 'size', undefined, transform); tags = findJsxTag(file, 'Spinner'); /* Need to reacquire tags because the tags have been modified since then! */ tags.forEach(val => { expect(val.getText()).toMatch('size={__migEnumMap[type]}'); }); }); }); }); });
8,001
0
petrpan-code/microsoft/fluentui/packages/codemods/src/helpers
petrpan-code/microsoft/fluentui/packages/codemods/src/helpers/tests/maybe.test.ts
import { Maybe, Something, Nothing } from '../maybe'; describe('Maybe', () => { it('new just has correct just value', () => { expect(Something(1).something).toBe(true); expect(Something('').something).toBe(true); }); it('new just has correct value', () => { expect(Something(0).value).toBe(0); expect(Something('').value).toBe(''); }); it('just will error if you pass it undefined', () => { let error = false; try { Something(undefined as unknown); } catch (_) { error = true; } expect(error).toBe(true); }); it('new nothing has correct just value', () => { expect(Nothing().something).toBe(false); }); it('maybe returns correct types', () => { const ma = Maybe(1); expect(ma.something).toBe(true); expect(ma.orElse(0)).toBe(1); const mb = Maybe(0); expect(mb.something).toBe(true); expect(mb.orElse(4)).toBe(0); const mc = Maybe(''); expect(mc.something).toBe(true); expect(mc.orElse('error')).toBe(''); }); it('then returns another maybe', () => { expect(Maybe(10).then(v => 'asd').something).toBeDefined(); expect(Maybe(undefined).then(v => 'asd').something).toBeDefined(); }); it('then returns nothing if undefined', () => { expect(Maybe(undefined).then(v => 'asd').something).toEqual(false); }); it('then returns new maybe if it has a value', () => { expect( Maybe('avalue') .then(v => 'good') .orElse('bad'), ).toEqual('good'); }); it('then returns single maybe if maybe returned', () => { expect( Maybe('foo') .then(v => Maybe('newValue')) .orElse('bad'), ).toEqual('newValue'); }); it('wraps undefined in Maybe correctly', () => { expect( Maybe('foo') .then<string>(v => undefined as unknown as string) .orElse('defaultValue'), ).toEqual('defaultValue'); }); it('flattens a nested maybe correctly', () => { expect(Maybe(Maybe('foo')).flatten().orElse('newValue')).toEqual('foo'); }); it('flattens a single maybe directly', () => { expect(Maybe('foo').flatten().orElse('newValue')).toEqual('foo'); }); it('flattens a single maybe directly', () => { expect( Maybe(Maybe(Maybe('foo'))) .flatten() .flatten() .orElse('newValue'), ).toEqual('foo'); }); });
8,002
0
petrpan-code/microsoft/fluentui/packages/codemods/src/helpers
petrpan-code/microsoft/fluentui/packages/codemods/src/helpers/tests/result.test.ts
import { Err, Ok, Result } from '../result'; const getOk = <T, Z>(ok: T, err: Z): Result<T, Z> => { return Ok<T, Z>(ok!); }; const getErr = <T, Z>(okay: T, err: Z): Result<T, Z> => { return Err<T, Z>(err!); }; describe('Result', () => { it('chained Okay value is evaluated correctly', () => { expect( getOk(3, '4') .chain(v => Ok(v + 3)) .okOrElse(100), ).toBe(6); }); it('errChained Err value is evaluated correctly', () => { expect( getErr(3, '4') .errChain(v => Err<number, number>(7)) .errOrElse(100), ).toBe(7); }); it('chained Err value is evaluated correctly', () => { expect( getErr(3, '4') .chain(v => Ok(1)) .okOrElse(100), ).toBe(100); }); it('chained Err value is evaluated correctly', () => { expect( getErr(3, '4') .errChain(v => Ok(1)) .okOrElse(100), ).toBe(1); }); it('chain returning a Err returns a Err correctly', () => { expect(getOk(3, '4').chain(v => Err('Error')).ok).toBe(false); }); it('errChain returning an Ok returns an Ok correctly', () => { expect(getOk(3, '4').chain(v => Ok('Error')).ok).toBe(true); }); it('Thens correctly on Ok', () => { expect( getOk(3, '4') .then(v => 30) .then(v => v.toString()) .okOrElse('Bad'), ).toBe('30'); }); it('Thens correctly on Err', () => { expect( getErr(3, '4') .then(v => 30) .then(v => v.toString()) .okOrElse('Bad'), ).toBe('Bad'); }); it('orThens correctly on Err', () => { expect( getErr(3, '4') .errThen(v => 30) .errThen(v => v.toString()) .errOrElse('Bad'), ).toBe('30'); }); it('orThens correctly on Ok', () => { expect( getOk(3, '4') .errThen(v => 30) .errThen(v => v.toString()) .errOrElse('Bad'), ).toBe('Bad'); }); it('resolve calls Ok function with Ok object value', () => { const spyLeft = jest.fn(); const spyRight = jest.fn(); getOk(3, '4').resolve(spyRight, spyLeft); expect(spyRight).toHaveBeenCalled(); expect(spyRight).toHaveBeenCalledWith(3); }); it('resolve calls Err function with Err object value', () => { const spyLeft = jest.fn(); const spyRight = jest.fn(); getErr(3, '4').resolve(spyRight, spyLeft); expect(spyLeft).toHaveBeenCalled(); expect(spyLeft).toHaveBeenCalledWith('4'); }); it('resolve calls Err function with Err object value after then', () => { const spyLeft = jest.fn(); const spyRight = jest.fn(); getErr(3, '4') .then(v => 10) .resolve(spyRight, spyLeft); expect(spyLeft).toHaveBeenCalled(); expect(spyLeft).toHaveBeenCalledWith('4'); }); });
8,006
0
petrpan-code/microsoft/fluentui/packages/codemods/src/modRunner
petrpan-code/microsoft/fluentui/packages/codemods/src/modRunner/tests/command.test.ts
import { CommandParser, CommandParserResult, yargsParse } from '../../command'; import { Ok } from '../../helpers/result'; describe('command parser', () => { describe('when called with a single argument', () => { let result: CommandParserResult; beforeAll(() => { result = new CommandParser().parseArgs(['node', 'foo', 'bar/baz']); }); it('does not direct the program to exit', () => { expect(result.shouldExit).toBeFalsy(); }); }); describe('parses string filters into an array', () => { let result: ReturnType<typeof yargsParse>; beforeAll(() => { result = yargsParse(['node', 'foo', 'bar/baz', '-n', 'one', 'two', '-e']); }); it('has two strings parsed', () => { expect(result.modNames!.length).toEqual(2); }); it('first string is one', () => { expect(result.modNames![0]).toEqual('one'); }); it('exclude is true', () => { expect(result.excludeMods).toEqual(true); }); }); describe('commands parses a filter correctly', () => { it('filters to include', () => { const result = new CommandParser().parseArgs(['node', 'foo', 'bar/baz', '-n', 'one', 'two']); expect( result.modsFilter({ name: 'one', run: () => { return Ok({ logs: [] }); }, }), ).toBe(true); }); it('filters to exclude', () => { const result = new CommandParser().parseArgs(['node', 'foo', 'bar/baz', '-n', 'one', 'two', '-e']); expect( result.modsFilter({ name: 'one', run: () => { return Ok({ logs: [] }); }, }), ).toBe(false); }); }); });
8,007
0
petrpan-code/microsoft/fluentui/packages/codemods/src/modRunner
petrpan-code/microsoft/fluentui/packages/codemods/src/modRunner/tests/filters.test.ts
import { getModFilter, getRegexFilter, getStringFilter } from '../modFilter'; import { Maybe } from '../../helpers/maybe'; import { Ok } from '../../helpers/result'; describe('modRunner tests', () => { it('gets a basic exact name match filter from string', () => { const filter = getStringFilter('hi'); expect(filter('hi')).toBe(true); expect(filter('h')).toBe(false); }); it('gets a basic regex filter from a string', () => { const filter = getRegexFilter('.+hi'); expect(filter('ohi')).toBe(true); expect(filter('booo')).toBe(false); expect(filter('hello hi there')).toBe(true); }); it('always returns true if no filters provided', () => { const modFilter = getModFilter({ stringFilter: Maybe([]), regexFilter: Maybe(['']) }); expect( modFilter({ name: 'ohi', run: () => { return Ok({ logs: [] }); }, }), ).toBe(true); expect( modFilter({ name: 'bar', run: () => { return Ok({ logs: [] }); }, }), ).toBe(true); expect( modFilter({ name: 'foo', run: () => { return Ok({ logs: [] }); }, }), ).toBe(true); }); it('gets a master filter based on a list of filters', () => { const modFilter = getModFilter({ stringFilter: Maybe(['hi']), regexFilter: Maybe(['.+zz']) }); expect( modFilter({ name: 'hi', run: () => { return Ok({ logs: [] }); }, }), ).toBe(true); expect( modFilter({ name: 'o zz o', run: () => { return Ok({ logs: [] }); }, }), ).toBe(true); expect( modFilter({ name: 'I wont be filtered!', run: () => { return Ok({ logs: [] }); }, }), ).toBe(false); }); });
8,008
0
petrpan-code/microsoft/fluentui/packages/codemods/src/modRunner
petrpan-code/microsoft/fluentui/packages/codemods/src/modRunner/tests/modRunner.test.ts
import { getModsPaths, getTsConfigs, runMods, getModsPattern, getModsRootPath, getEnabledMods, } from '../runnerUtilities'; import { CodeMod, CodeModResult } from '../../codeMods/types'; import { Maybe, Nothing } from '../../helpers/maybe'; import { Ok } from '../../helpers/result'; describe('modRunner tests', () => { it('gets the appropriate path to mods based on current dir', () => { const modPath = getModsRootPath().replace(/\\/g, '/'); expect(modPath).toEqual(`${process.cwd().replace(/\\/g, '/')}/src/modRunner/../codeMods/mods`); }); it('returns the right paths to run for mods', () => { const gottenPaths = getModsPaths(`${process.cwd()}/src/modRunner/tests/mocks/MockMods`, getModsPattern(true)); expect(gottenPaths.length).toEqual(2); expect(gottenPaths[0]).toContain('CodeMod.mock.ts'); }); it('only returns .js files when includeTs is false', () => { const gottenPaths = getModsPaths(`${process.cwd()}/src/modRunner/tests/mocks/MockMods`, getModsPattern(false)); expect(gottenPaths.length).toEqual(1); expect(gottenPaths[0]).toContain('JSMock.mod.js'); }); it('finds the right ts-config files', () => { const files = getTsConfigs(`${process.cwd()}/src/modRunner/tests/mocks/MockProject`); expect(files.length).toEqual(2); expect(files[0]).toContain('tsconfig.json'); }); it('runs all mods', () => { let runCount = 0; const runCallBack = (foo: string): CodeModResult => { runCount = runCount + 1; return Ok({ logs: [] }); }; const mods: CodeMod<string>[] = [ { name: 'a', run: runCallBack, version: '1.1.1', }, { name: 'b', run: runCallBack, version: '1.1.1', }, { name: 'c', run: runCallBack, version: '1.1.1', }, ]; runMods(mods, [''], () => undefined); expect(runCount).toEqual(3); }); it('filters enabled and nothing Mods', () => { const runcallBack = (foo: string): CodeModResult => { return Ok({ logs: [] }); }; // use a generator to simulate getting each mod back function* modGen(): Generator<Maybe<CodeMod<string>>> { yield Maybe({ name: 'a', run: runcallBack, }); yield Maybe({ name: 'b', run: runcallBack, enabled: true, }); yield Maybe({ name: 'c', run: runcallBack, }); yield Nothing(); } const gen = modGen(); const filtered = getEnabledMods( console, () => ['1', '2', '3', '4'], () => gen.next().value, ); expect(filtered.length).toEqual(1); expect(filtered[0].name).toEqual('b'); }); });
8,009
0
petrpan-code/microsoft/fluentui/packages/codemods/src/modRunner
petrpan-code/microsoft/fluentui/packages/codemods/src/modRunner/tests/upgrade.test.ts
import { _upgradeInternal } from '../../upgrade'; import * as path from 'path'; import * as fs from 'fs-extra'; import * as os from 'os'; import { getTsConfigs } from '../runnerUtilities'; const tempDir = os.tmpdir(); const tempPath = path.join(tempDir, 'codemods'); const startingPath = process.cwd(); describe('modRunner tests', () => { let temp: string = ''; beforeEach(() => { temp = fs.mkdtempSync(tempPath); }); afterEach(() => { fs.removeSync(temp); }); it('saves syncronously correctly', () => { const saveAsync = jest.fn(); const saveSync = jest.fn(); try { fs.copySync(path.join(__dirname, '/mocks/MockProject'), temp); process.chdir(temp); _upgradeInternal( { modsFilter: () => true, }, { getTsConfigs: () => getTsConfigs(temp), saveAsync: saveAsync, saveSync: saveSync }, ); expect(saveAsync).toHaveBeenCalled(); } finally { process.chdir(startingPath); } }); it('saves asynchronously correctly', () => { const saveAsync = jest.fn(); const saveSync = jest.fn(); try { fs.copySync(path.join(__dirname, '/mocks/MockProject'), temp); process.chdir(temp); _upgradeInternal( { modsFilter: () => true, saveSync: true, }, { getTsConfigs: () => getTsConfigs(temp), saveAsync: saveAsync, saveSync: saveSync }, ); expect(saveSync).toHaveBeenCalled(); } finally { process.chdir(startingPath); } }); });
8,047
0
petrpan-code/microsoft/fluentui/packages/cra-template
petrpan-code/microsoft/fluentui/packages/cra-template/scripts/test.ts
import fs from 'fs'; import path from 'path'; import semver from 'semver'; import { addResolutionPathsForProjectPackages, packProjectPackages, performBrowserTest, prepareTempDirs, log, shEcho, prepareCreateReactApp, TempPaths, } from '@fluentui/scripts-projects-test'; // eslint-disable-next-line @typescript-eslint/no-explicit-any function readJson(filePath: string): Record<string, any> { return JSON.parse(fs.readFileSync(filePath, 'utf-8')); } // This test is sort of like `packages/fluentui/projects-test/src/createReactApp.ts`, but it uses // a custom local template rather than making a generic TS project and adding our project as a dep. // So they share some logic, but can't be completely merged (and this test shouldn't go under // projects-test because it needs to run under different scoped build conditions). /** * Ensure the template in this branch is requesting the version of @fluentui/react from this branch. * This will probably only be an issue if there's a major version bump. */ function verifyVersion() { const templateJson = readJson(path.resolve(__dirname, '../template.json')); const templateVersion = templateJson.package.dependencies['@fluentui/react']; const reactPackageJson = readJson(path.resolve(__dirname, '../../react/package.json')); const actualVersion = reactPackageJson.version; if (!semver.satisfies(actualVersion, templateVersion)) { console.error( `@fluentui/react version ${actualVersion} does not satisfy template version range ${templateVersion}.`, ); console.error('Please update the @fluentui/react version listed in cra-template/template.json.'); process.exit(1); } } /** * If we tested the template as-is, it would install the latest packages from npm, which is pointless. * Instead, pack up the locally-built packages and make a copy of the template which references them. */ async function prepareTemplate(logger: Function, tempPaths: TempPaths) { await packProjectPackages(logger, '@fluentui/react'); const templatePath = path.join(tempPaths.root, 'cra-template'); const packageJson = readJson(path.resolve(__dirname, '../package.json')); // Copy only the template files that would be installed from npm const filesToCopy = [...packageJson.files, 'package.json']; const rootDir = path.resolve(__dirname, '..'); for (const file of filesToCopy) { fs.cpSync(path.resolve(rootDir, file), path.join(templatePath, file), { recursive: true }); } await addResolutionPathsForProjectPackages(templatePath, true /*isTemplateJson*/); return templatePath; } /** * Tests the following scenario: * - Copy the template to a temp directory * - Modify it to reference packed versions of the local packages * - Use the template to create a test app * - Build and test the test app */ async function runE2ETest() { const testName = '@fluentui/cra-template'; const logger = log(testName); const tempPaths = prepareTempDirs(`${path.basename(testName)}-`); logger(`✔️ Temporary directories created under ${tempPaths.root}`); logger('STEP 1. Update template to reference local packages'); const templatePath = await prepareTemplate(logger, tempPaths); logger('STEP 2. Create test React app from template'); await prepareCreateReactApp(tempPaths, `file:${templatePath}`); await shEcho('yarn add cross-env', tempPaths.testApp); logger(`✔️ Test React app is successfully created: ${tempPaths.testApp}`); logger('STEP 3. Build test app'); await shEcho(`yarn cross-env CI=1 yarn build`, tempPaths.testApp); logger('STEP 4. Run test app tests'); await shEcho(`yarn cross-env CI=1 yarn test`, tempPaths.testApp); logger('STEP 5. Load the test app in the browser'); await performBrowserTest(path.join(tempPaths.testApp, 'build')); logger('✔️ Browser test passed'); } (async () => { verifyVersion(); await runE2ETest(); })().catch(err => { console.error(err.stack || err); process.exit(1); });
8,054
0
petrpan-code/microsoft/fluentui/packages/cra-template/template
petrpan-code/microsoft/fluentui/packages/cra-template/template/src/App.test.tsx
import React from 'react'; import { render, screen } from '@testing-library/react'; import { App } from './App'; it('renders "Welcome to Your Fluent UI App"', () => { render(<App />); const linkElement = screen.getByText(/Welcome to Your Fluent UI App/i); expect(linkElement).toBeInTheDocument(); });
8,078
0
petrpan-code/microsoft/fluentui/packages/date-time-utilities/src
petrpan-code/microsoft/fluentui/packages/date-time-utilities/src/dateFormatting/dateFormatting.test.ts
import { formatDay, formatMonth, formatMonthDayYear, formatMonthYear, formatYear, DEFAULT_DATE_GRID_STRINGS, } from './dateFormatting.defaults'; import { MonthOfYear } from '../dateValues/dateValues'; const date = new Date(2016, MonthOfYear.April, 1); describe('formatDay', () => { it('returns default format', () => { const result = formatDay(date); expect(result).toBe('1'); }); }); describe('formatMonth', () => { it('returns default format', () => { const result = formatMonth(date, DEFAULT_DATE_GRID_STRINGS); expect(result).toBe('April'); }); }); describe('formatMonthDayYear', () => { it('returns default format', () => { const result = formatMonthDayYear(date, DEFAULT_DATE_GRID_STRINGS); expect(result).toBe('April 1, 2016'); }); }); describe('formatMonthYear', () => { it('returns default format', () => { const result = formatMonthYear(date, DEFAULT_DATE_GRID_STRINGS); expect(result).toBe('April 2016'); }); }); describe('formatYear', () => { it('returns default format', () => { const result = formatYear(date); expect(result).toBe('2016'); }); });
8,082
0
petrpan-code/microsoft/fluentui/packages/date-time-utilities/src
petrpan-code/microsoft/fluentui/packages/date-time-utilities/src/dateGrid/findAvailableDate.test.ts
import { IAvailableDateOptions } from './dateGrid.types'; import * as DateGrid from './findAvailableDate'; import { MonthOfYear } from '../dateValues/dateValues'; describe('findAvailableDate', () => { const defaultOptions: IAvailableDateOptions = { initialDate: new Date(2016, MonthOfYear.April, 1), targetDate: new Date(2016, MonthOfYear.April, 2), direction: 1, }; it('returns next available date', () => { const result = DateGrid.findAvailableDate(defaultOptions); const expected = defaultOptions.targetDate; expect(result).toEqual(expected); }); it('returns next available date, within date restrictions', () => { const minDateOptions = { ...defaultOptions }; minDateOptions.restrictedDates = [new Date(2016, MonthOfYear.April, 2), new Date(2016, MonthOfYear.April, 3)]; const result = DateGrid.findAvailableDate(minDateOptions); const expected = new Date(2016, MonthOfYear.April, 4); expect(result).toEqual(expected); }); it('returns previous available date', () => { const reverseOptions: IAvailableDateOptions = { initialDate: new Date(2016, MonthOfYear.April, 2), targetDate: new Date(2016, MonthOfYear.April, 1), direction: -1, }; const result = DateGrid.findAvailableDate(reverseOptions); const expected = new Date(2016, MonthOfYear.April, 1); expect(result).toEqual(expected); }); it('returns previous available date, within date restrictions', () => { const reverseOptions: IAvailableDateOptions = { initialDate: new Date(2016, MonthOfYear.April, 2), targetDate: new Date(2016, MonthOfYear.April, 1), direction: -1, restrictedDates: [new Date(2016, MonthOfYear.April, 1), new Date(2016, MonthOfYear.April, 2)], }; const result = DateGrid.findAvailableDate(reverseOptions); const expected = new Date(2016, MonthOfYear.March, 31); expect(result).toEqual(expected); }); });
8,084
0
petrpan-code/microsoft/fluentui/packages/date-time-utilities/src
petrpan-code/microsoft/fluentui/packages/date-time-utilities/src/dateGrid/getBoundedDateRange.test.ts
import * as DateGrid from './getBoundedDateRange'; import { MonthOfYear } from '../dateValues/dateValues'; describe('getBoundedDateRange', () => { const defaultRange = [ new Date(2016, MonthOfYear.April, 1), new Date(2016, MonthOfYear.April, 2), new Date(2016, MonthOfYear.April, 3), new Date(2016, MonthOfYear.April, 4), ]; it('returns same range if min and max dates are empty', () => { const result = DateGrid.getBoundedDateRange(defaultRange); const expected = defaultRange; expect(result).toEqual(expected); }); it('returns adjusted range if min date is present', () => { const result = DateGrid.getBoundedDateRange(defaultRange, new Date(2016, MonthOfYear.April, 3)); const expected = [new Date(2016, MonthOfYear.April, 3), new Date(2016, MonthOfYear.April, 4)]; expect(result).toEqual(expected); }); it('returns adjusted range if max date is present', () => { const result = DateGrid.getBoundedDateRange(defaultRange, undefined, new Date(2016, MonthOfYear.April, 2)); const expected = [new Date(2016, MonthOfYear.April, 1), new Date(2016, MonthOfYear.April, 2)]; expect(result).toEqual(expected); }); it('returns adjusted range if min and max dates are present', () => { const result = DateGrid.getBoundedDateRange( defaultRange, new Date(2016, MonthOfYear.April, 3), new Date(2016, MonthOfYear.April, 3), ); const expected = [new Date(2016, MonthOfYear.April, 3)]; expect(result).toEqual(expected); }); });
8,086
0
petrpan-code/microsoft/fluentui/packages/date-time-utilities/src
petrpan-code/microsoft/fluentui/packages/date-time-utilities/src/dateGrid/getDateRangeTypeToUse.test.ts
import { DateRangeType, DayOfWeek } from '../dateValues/dateValues'; import * as DateGrid from './getDateRangeTypeToUse'; describe('getDateRangeTypeToUse', () => { it('returns incoming range type if working days are empty', () => { const resultDay = DateGrid.getDateRangeTypeToUse(DateRangeType.Day, undefined, DayOfWeek.Sunday); expect(resultDay).toBe(DateRangeType.Day); const resultWeek = DateGrid.getDateRangeTypeToUse(DateRangeType.Week, undefined, DayOfWeek.Sunday); expect(resultWeek).toBe(DateRangeType.Week); const resultMonth = DateGrid.getDateRangeTypeToUse(DateRangeType.Month, undefined, DayOfWeek.Sunday); expect(resultMonth).toBe(DateRangeType.Month); const resultWorkWeek = DateGrid.getDateRangeTypeToUse(DateRangeType.WorkWeek, undefined, DayOfWeek.Sunday); expect(resultWorkWeek).toBe(DateRangeType.WorkWeek); }); it('returns Week range type if working days are non-contiguous and incoming type is WorkWeek', () => { const resultWorkWeek = DateGrid.getDateRangeTypeToUse( DateRangeType.WorkWeek, [DayOfWeek.Monday, DayOfWeek.Wednesday], DayOfWeek.Sunday, ); expect(resultWorkWeek).toBe(DateRangeType.Week); }); it('returns WorkWeek range type if working days are contiguous and incoming type is WorkWeek', () => { const resultWorkWeek = DateGrid.getDateRangeTypeToUse( DateRangeType.WorkWeek, [DayOfWeek.Monday, DayOfWeek.Tuesday], DayOfWeek.Sunday, ); expect(resultWorkWeek).toBe(DateRangeType.WorkWeek); }); // eslint-disable-next-line @fluentui/max-len it('returns WorkWeek range type if working days are not contiguous from Saturday to Sunday and incoming type is WorkWeek', () => { const resultWorkWeek = DateGrid.getDateRangeTypeToUse( DateRangeType.WorkWeek, [DayOfWeek.Saturday, DayOfWeek.Sunday], DayOfWeek.Sunday, ); expect(resultWorkWeek).toBe(DateRangeType.Week); }); // eslint-disable-next-line @fluentui/max-len it('returns WorkWeek range type if working days are contiguous from Saturday to Sunday and incoming type is WorkWeek', () => { const resultWorkWeek = DateGrid.getDateRangeTypeToUse( DateRangeType.WorkWeek, [DayOfWeek.Saturday, DayOfWeek.Sunday], DayOfWeek.Monday, ); expect(resultWorkWeek).toBe(DateRangeType.WorkWeek); }); });
8,088
0
petrpan-code/microsoft/fluentui/packages/date-time-utilities/src
petrpan-code/microsoft/fluentui/packages/date-time-utilities/src/dateGrid/getDayGrid.test.ts
import { DateRangeType, DayOfWeek, FirstWeekOfYear } from '../dateValues/dateValues'; import { addDays, compareDates } from '../dateMath/dateMath'; import { IDayGridOptions } from './dateGrid.types'; import * as DateGrid from './getDayGrid'; import { IDay } from './dateGrid.types'; describe('getDayGrid', () => { const defaultDate = new Date('Apr 1 2016'); const defaultOptions: IDayGridOptions = { selectedDate: defaultDate, navigatedDate: defaultDate, firstDayOfWeek: DayOfWeek.Sunday, firstWeekOfYear: FirstWeekOfYear.FirstDay, dateRangeType: DateRangeType.Day, }; const transitionWeekCount = 2; /** * Adding custom date normalization, since we need to ensure the consistency across different timezones and locales * and setting timezone via TZ environment variable currently does not work * on Windows (see https://github.com/nodejs/node/issues/4230 and https://github.com/nodejs/node/issues/31478) * */ const normalizeDay = (day: IDay) => { const date = day.originalDate; const offset = day.originalDate.getTimezoneOffset(); date.setUTCMinutes(-offset); date.setUTCSeconds(0); date.setUTCMilliseconds(0); return { date: day.date, isInBounds: day.isInBounds, isInMonth: day.isInMonth, isSelected: day.isSelected, isToday: day.isToday, key: date.toUTCString(), originalDate: date, }; }; const countDays = (days: IDay[][], condition: (day: IDay) => boolean) => { let count = 0; for (const week of days) { for (const day of week) { if (condition(day)) { count += 1; } } } return count; }; it('returns matrix with days', () => { const result = DateGrid.getDayGrid(defaultOptions); const resultUTC = result.map(week => week.map(day => normalizeDay(day))); expect(resultUTC).toMatchSnapshot(); }); it('returns grid starting with proper day', () => { const result = DateGrid.getDayGrid({ ...defaultOptions, firstDayOfWeek: DayOfWeek.Wednesday }); expect(result[0][0].originalDate.getDay()).toBe(DayOfWeek.Wednesday); }); it('returns grid with proper amount of weeks', () => { const weekCount = 6; const result = DateGrid.getDayGrid({ ...defaultOptions, weeksToShow: weekCount }); expect(result.length).toBe(weekCount + transitionWeekCount); }); it('returns grid with proper amount of selected days', () => { const daysToSelect = 6; const result = DateGrid.getDayGrid({ ...defaultOptions, dateRangeType: DateRangeType.Day, daysToSelectInDayView: daysToSelect, }); expect(countDays(result, day => day.isSelected)).toBe(daysToSelect); }); it('returns grid with no selected days', () => { const result = DateGrid.getDayGrid({ ...defaultOptions, selectedDate: new Date(0) }); expect(countDays(result, day => day.isSelected)).toBe(0); }); it('returns grid with proper amount of weeks', () => { const result = DateGrid.getDayGrid({ ...defaultOptions, minDate: addDays(defaultDate, -1), maxDate: addDays(defaultDate, 1), }); expect(countDays(result, day => day.isInBounds)).toBe(3); }); it('returns grid with proper today', () => { const today = addDays(defaultDate, 5); const result = DateGrid.getDayGrid({ ...defaultOptions, today, }); expect(countDays(result, day => day.isToday)).toBe(1); expect(countDays(result, day => compareDates(today, day.originalDate) && day.isToday)).toBe(1); }); it('returns grid with proper amount of work week days when over multiple work weeks', () => { const result = DateGrid.getDayGrid({ ...defaultOptions, workWeekDays: [DayOfWeek.Saturday, DayOfWeek.Sunday, DayOfWeek.Monday], dateRangeType: DateRangeType.WorkWeek, firstDayOfWeek: DayOfWeek.Monday, }); expect(countDays(result, day => day.isSelected)).toBe(7); }); it('returns grid with proper amount of work week days when over single work weeks', () => { const result = DateGrid.getDayGrid({ ...defaultOptions, workWeekDays: [DayOfWeek.Saturday, DayOfWeek.Sunday, DayOfWeek.Monday], dateRangeType: DateRangeType.WorkWeek, firstDayOfWeek: DayOfWeek.Tuesday, }); expect(countDays(result, day => day.isSelected)).toBe(3); }); });
8,091
0
petrpan-code/microsoft/fluentui/packages/date-time-utilities/src
petrpan-code/microsoft/fluentui/packages/date-time-utilities/src/dateGrid/isAfterMaxDate.test.ts
import { IRestrictedDatesOptions } from './dateGrid.types'; import * as DateGrid from './isAfterMaxDate'; import { MonthOfYear } from '../dateValues/dateValues'; describe('isAfterMaxDate', () => { const date = new Date(2016, MonthOfYear.April, 3); it('returns false if max date is empty', () => { const options: IRestrictedDatesOptions = {}; const result = DateGrid.isAfterMaxDate(date, options); expect(result).toBeFalsy(); }); it('returns false if max date is greater than date', () => { const options: IRestrictedDatesOptions = { maxDate: new Date(2016, MonthOfYear.April, 7), }; const result = DateGrid.isAfterMaxDate(date, options); expect(result).toBeFalsy(); }); it('returns false if max date is equal to date', () => { const options: IRestrictedDatesOptions = { maxDate: new Date(2016, MonthOfYear.April, 3), }; const result = DateGrid.isAfterMaxDate(date, options); expect(result).toBeFalsy(); }); it('returns true if max date is less than date', () => { const options: IRestrictedDatesOptions = { maxDate: new Date(2016, MonthOfYear.April, 1), }; const result = DateGrid.isAfterMaxDate(date, options); expect(result).toBeTruthy(); }); });
8,093
0
petrpan-code/microsoft/fluentui/packages/date-time-utilities/src
petrpan-code/microsoft/fluentui/packages/date-time-utilities/src/dateGrid/isBeforeMinDate.test.ts
import * as DateGrid from './isBeforeMinDate'; import { IRestrictedDatesOptions } from './dateGrid.types'; import { MonthOfYear } from '../dateValues/dateValues'; describe('isBeforeMinDate', () => { const date = new Date(2016, MonthOfYear.April, 3); it('returns false if min date is empty', () => { const options: IRestrictedDatesOptions = {}; const result = DateGrid.isBeforeMinDate(date, options); expect(result).toBeFalsy(); }); it('returns true if min date is greater than date', () => { const options: IRestrictedDatesOptions = { minDate: new Date(2016, MonthOfYear.April, 7), }; const result = DateGrid.isBeforeMinDate(date, options); expect(result).toBeTruthy(); }); it('returns false if min date is equal to date', () => { const options: IRestrictedDatesOptions = { minDate: new Date(2016, MonthOfYear.April, 3), }; const result = DateGrid.isBeforeMinDate(date, options); expect(result).toBeFalsy(); }); it('returns false if min date is less than date', () => { const options: IRestrictedDatesOptions = { minDate: new Date(2016, MonthOfYear.April, 1), }; const result = DateGrid.isBeforeMinDate(date, options); expect(result).toBeFalsy(); }); });
8,095
0
petrpan-code/microsoft/fluentui/packages/date-time-utilities/src
petrpan-code/microsoft/fluentui/packages/date-time-utilities/src/dateGrid/isContiguous.test.ts
import { DayOfWeek } from '../dateValues/dateValues'; import { isContiguous } from './isContiguous'; describe('isContiguous', () => { it('returns false if non-consecutive days', () => { const result = isContiguous([DayOfWeek.Friday, DayOfWeek.Sunday], false, DayOfWeek.Friday); expect(result).toBeFalsy(); }); it('returns true if consecutive work days', () => { const result = isContiguous( [DayOfWeek.Friday, DayOfWeek.Thursday, DayOfWeek.Wednesday, DayOfWeek.Tuesday, DayOfWeek.Monday], true, DayOfWeek.Monday, ); expect(result).toBeTruthy(); }); it('returns true if weekend and not one week', () => { const result = isContiguous([DayOfWeek.Saturday, DayOfWeek.Sunday], false, DayOfWeek.Sunday); expect(result).toBeTruthy(); }); it('returns false if weekend and one week', () => { const result = isContiguous([DayOfWeek.Saturday, DayOfWeek.Sunday], true, DayOfWeek.Sunday); expect(result).toBeFalsy(); }); });
8,097
0
petrpan-code/microsoft/fluentui/packages/date-time-utilities/src
petrpan-code/microsoft/fluentui/packages/date-time-utilities/src/dateGrid/isRestrictedDate.test.ts
import * as DateGrid from './isRestrictedDate'; import { IRestrictedDatesOptions } from './dateGrid.types'; import { MonthOfYear } from '../dateValues/dateValues'; describe('isRestrictedDate', () => { const date = new Date(2016, MonthOfYear.April, 3); it('returns false if options are empty', () => { const options: IRestrictedDatesOptions = {}; const result = DateGrid.isRestrictedDate(date, options); expect(result).toBeFalsy(); }); it('returns true if restricted dates include date', () => { const options: IRestrictedDatesOptions = { restrictedDates: [new Date(2016, MonthOfYear.April, 3)], }; const result = DateGrid.isRestrictedDate(date, options); expect(result).toBeTruthy(); }); });
8,099
0
petrpan-code/microsoft/fluentui/packages/date-time-utilities/src/dateGrid
petrpan-code/microsoft/fluentui/packages/date-time-utilities/src/dateGrid/__snapshots__/getDayGrid.test.ts.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`getDayGrid returns matrix with days 1`] = ` Array [ Array [ Object { "date": "20", "isInBounds": true, "isInMonth": false, "isSelected": false, "isToday": false, "key": "Sun, 20 Mar 2016 00:00:00 GMT", "originalDate": 2016-03-20T00:00:00.000Z, }, Object { "date": "21", "isInBounds": true, "isInMonth": false, "isSelected": false, "isToday": false, "key": "Mon, 21 Mar 2016 00:00:00 GMT", "originalDate": 2016-03-21T00:00:00.000Z, }, Object { "date": "22", "isInBounds": true, "isInMonth": false, "isSelected": false, "isToday": false, "key": "Tue, 22 Mar 2016 00:00:00 GMT", "originalDate": 2016-03-22T00:00:00.000Z, }, Object { "date": "23", "isInBounds": true, "isInMonth": false, "isSelected": false, "isToday": false, "key": "Wed, 23 Mar 2016 00:00:00 GMT", "originalDate": 2016-03-23T00:00:00.000Z, }, Object { "date": "24", "isInBounds": true, "isInMonth": false, "isSelected": false, "isToday": false, "key": "Thu, 24 Mar 2016 00:00:00 GMT", "originalDate": 2016-03-24T00:00:00.000Z, }, Object { "date": "25", "isInBounds": true, "isInMonth": false, "isSelected": false, "isToday": false, "key": "Fri, 25 Mar 2016 00:00:00 GMT", "originalDate": 2016-03-25T00:00:00.000Z, }, Object { "date": "26", "isInBounds": true, "isInMonth": false, "isSelected": false, "isToday": false, "key": "Sat, 26 Mar 2016 00:00:00 GMT", "originalDate": 2016-03-26T00:00:00.000Z, }, ], Array [ Object { "date": "27", "isInBounds": true, "isInMonth": false, "isSelected": false, "isToday": false, "key": "Sun, 27 Mar 2016 00:00:00 GMT", "originalDate": 2016-03-27T00:00:00.000Z, }, Object { "date": "28", "isInBounds": true, "isInMonth": false, "isSelected": false, "isToday": false, "key": "Mon, 28 Mar 2016 00:00:00 GMT", "originalDate": 2016-03-28T00:00:00.000Z, }, Object { "date": "29", "isInBounds": true, "isInMonth": false, "isSelected": false, "isToday": false, "key": "Tue, 29 Mar 2016 00:00:00 GMT", "originalDate": 2016-03-29T00:00:00.000Z, }, Object { "date": "30", "isInBounds": true, "isInMonth": false, "isSelected": false, "isToday": false, "key": "Wed, 30 Mar 2016 00:00:00 GMT", "originalDate": 2016-03-30T00:00:00.000Z, }, Object { "date": "31", "isInBounds": true, "isInMonth": false, "isSelected": false, "isToday": false, "key": "Thu, 31 Mar 2016 00:00:00 GMT", "originalDate": 2016-03-31T00:00:00.000Z, }, Object { "date": "1", "isInBounds": true, "isInMonth": true, "isSelected": true, "isToday": false, "key": "Fri, 01 Apr 2016 00:00:00 GMT", "originalDate": 2016-04-01T00:00:00.000Z, }, Object { "date": "2", "isInBounds": true, "isInMonth": true, "isSelected": false, "isToday": false, "key": "Sat, 02 Apr 2016 00:00:00 GMT", "originalDate": 2016-04-02T00:00:00.000Z, }, ], Array [ Object { "date": "3", "isInBounds": true, "isInMonth": true, "isSelected": false, "isToday": false, "key": "Sun, 03 Apr 2016 00:00:00 GMT", "originalDate": 2016-04-03T00:00:00.000Z, }, Object { "date": "4", "isInBounds": true, "isInMonth": true, "isSelected": false, "isToday": false, "key": "Mon, 04 Apr 2016 00:00:00 GMT", "originalDate": 2016-04-04T00:00:00.000Z, }, Object { "date": "5", "isInBounds": true, "isInMonth": true, "isSelected": false, "isToday": false, "key": "Tue, 05 Apr 2016 00:00:00 GMT", "originalDate": 2016-04-05T00:00:00.000Z, }, Object { "date": "6", "isInBounds": true, "isInMonth": true, "isSelected": false, "isToday": false, "key": "Wed, 06 Apr 2016 00:00:00 GMT", "originalDate": 2016-04-06T00:00:00.000Z, }, Object { "date": "7", "isInBounds": true, "isInMonth": true, "isSelected": false, "isToday": false, "key": "Thu, 07 Apr 2016 00:00:00 GMT", "originalDate": 2016-04-07T00:00:00.000Z, }, Object { "date": "8", "isInBounds": true, "isInMonth": true, "isSelected": false, "isToday": false, "key": "Fri, 08 Apr 2016 00:00:00 GMT", "originalDate": 2016-04-08T00:00:00.000Z, }, Object { "date": "9", "isInBounds": true, "isInMonth": true, "isSelected": false, "isToday": false, "key": "Sat, 09 Apr 2016 00:00:00 GMT", "originalDate": 2016-04-09T00:00:00.000Z, }, ], Array [ Object { "date": "10", "isInBounds": true, "isInMonth": true, "isSelected": false, "isToday": false, "key": "Sun, 10 Apr 2016 00:00:00 GMT", "originalDate": 2016-04-10T00:00:00.000Z, }, Object { "date": "11", "isInBounds": true, "isInMonth": true, "isSelected": false, "isToday": false, "key": "Mon, 11 Apr 2016 00:00:00 GMT", "originalDate": 2016-04-11T00:00:00.000Z, }, Object { "date": "12", "isInBounds": true, "isInMonth": true, "isSelected": false, "isToday": false, "key": "Tue, 12 Apr 2016 00:00:00 GMT", "originalDate": 2016-04-12T00:00:00.000Z, }, Object { "date": "13", "isInBounds": true, "isInMonth": true, "isSelected": false, "isToday": false, "key": "Wed, 13 Apr 2016 00:00:00 GMT", "originalDate": 2016-04-13T00:00:00.000Z, }, Object { "date": "14", "isInBounds": true, "isInMonth": true, "isSelected": false, "isToday": false, "key": "Thu, 14 Apr 2016 00:00:00 GMT", "originalDate": 2016-04-14T00:00:00.000Z, }, Object { "date": "15", "isInBounds": true, "isInMonth": true, "isSelected": false, "isToday": false, "key": "Fri, 15 Apr 2016 00:00:00 GMT", "originalDate": 2016-04-15T00:00:00.000Z, }, Object { "date": "16", "isInBounds": true, "isInMonth": true, "isSelected": false, "isToday": false, "key": "Sat, 16 Apr 2016 00:00:00 GMT", "originalDate": 2016-04-16T00:00:00.000Z, }, ], Array [ Object { "date": "17", "isInBounds": true, "isInMonth": true, "isSelected": false, "isToday": false, "key": "Sun, 17 Apr 2016 00:00:00 GMT", "originalDate": 2016-04-17T00:00:00.000Z, }, Object { "date": "18", "isInBounds": true, "isInMonth": true, "isSelected": false, "isToday": false, "key": "Mon, 18 Apr 2016 00:00:00 GMT", "originalDate": 2016-04-18T00:00:00.000Z, }, Object { "date": "19", "isInBounds": true, "isInMonth": true, "isSelected": false, "isToday": false, "key": "Tue, 19 Apr 2016 00:00:00 GMT", "originalDate": 2016-04-19T00:00:00.000Z, }, Object { "date": "20", "isInBounds": true, "isInMonth": true, "isSelected": false, "isToday": false, "key": "Wed, 20 Apr 2016 00:00:00 GMT", "originalDate": 2016-04-20T00:00:00.000Z, }, Object { "date": "21", "isInBounds": true, "isInMonth": true, "isSelected": false, "isToday": false, "key": "Thu, 21 Apr 2016 00:00:00 GMT", "originalDate": 2016-04-21T00:00:00.000Z, }, Object { "date": "22", "isInBounds": true, "isInMonth": true, "isSelected": false, "isToday": false, "key": "Fri, 22 Apr 2016 00:00:00 GMT", "originalDate": 2016-04-22T00:00:00.000Z, }, Object { "date": "23", "isInBounds": true, "isInMonth": true, "isSelected": false, "isToday": false, "key": "Sat, 23 Apr 2016 00:00:00 GMT", "originalDate": 2016-04-23T00:00:00.000Z, }, ], Array [ Object { "date": "24", "isInBounds": true, "isInMonth": true, "isSelected": false, "isToday": false, "key": "Sun, 24 Apr 2016 00:00:00 GMT", "originalDate": 2016-04-24T00:00:00.000Z, }, Object { "date": "25", "isInBounds": true, "isInMonth": true, "isSelected": false, "isToday": false, "key": "Mon, 25 Apr 2016 00:00:00 GMT", "originalDate": 2016-04-25T00:00:00.000Z, }, Object { "date": "26", "isInBounds": true, "isInMonth": true, "isSelected": false, "isToday": false, "key": "Tue, 26 Apr 2016 00:00:00 GMT", "originalDate": 2016-04-26T00:00:00.000Z, }, Object { "date": "27", "isInBounds": true, "isInMonth": true, "isSelected": false, "isToday": false, "key": "Wed, 27 Apr 2016 00:00:00 GMT", "originalDate": 2016-04-27T00:00:00.000Z, }, Object { "date": "28", "isInBounds": true, "isInMonth": true, "isSelected": false, "isToday": false, "key": "Thu, 28 Apr 2016 00:00:00 GMT", "originalDate": 2016-04-28T00:00:00.000Z, }, Object { "date": "29", "isInBounds": true, "isInMonth": true, "isSelected": false, "isToday": false, "key": "Fri, 29 Apr 2016 00:00:00 GMT", "originalDate": 2016-04-29T00:00:00.000Z, }, Object { "date": "30", "isInBounds": true, "isInMonth": true, "isSelected": false, "isToday": false, "key": "Sat, 30 Apr 2016 00:00:00 GMT", "originalDate": 2016-04-30T00:00:00.000Z, }, ], Array [ Object { "date": "1", "isInBounds": true, "isInMonth": false, "isSelected": false, "isToday": false, "key": "Sun, 01 May 2016 00:00:00 GMT", "originalDate": 2016-05-01T00:00:00.000Z, }, Object { "date": "2", "isInBounds": true, "isInMonth": false, "isSelected": false, "isToday": false, "key": "Mon, 02 May 2016 00:00:00 GMT", "originalDate": 2016-05-02T00:00:00.000Z, }, Object { "date": "3", "isInBounds": true, "isInMonth": false, "isSelected": false, "isToday": false, "key": "Tue, 03 May 2016 00:00:00 GMT", "originalDate": 2016-05-03T00:00:00.000Z, }, Object { "date": "4", "isInBounds": true, "isInMonth": false, "isSelected": false, "isToday": false, "key": "Wed, 04 May 2016 00:00:00 GMT", "originalDate": 2016-05-04T00:00:00.000Z, }, Object { "date": "5", "isInBounds": true, "isInMonth": false, "isSelected": false, "isToday": false, "key": "Thu, 05 May 2016 00:00:00 GMT", "originalDate": 2016-05-05T00:00:00.000Z, }, Object { "date": "6", "isInBounds": true, "isInMonth": false, "isSelected": false, "isToday": false, "key": "Fri, 06 May 2016 00:00:00 GMT", "originalDate": 2016-05-06T00:00:00.000Z, }, Object { "date": "7", "isInBounds": true, "isInMonth": false, "isSelected": false, "isToday": false, "key": "Sat, 07 May 2016 00:00:00 GMT", "originalDate": 2016-05-07T00:00:00.000Z, }, ], ] `;
8,100
0
petrpan-code/microsoft/fluentui/packages/date-time-utilities/src
petrpan-code/microsoft/fluentui/packages/date-time-utilities/src/dateMath/dateMath.test.ts
import { DayOfWeek, DateRangeType } from '../dateValues/dateValues'; import * as DateMath from './dateMath'; enum Months { Jan = 0, Feb = 1, Mar = 2, Apr = 3, May = 4, Jun = 5, Jul = 6, Aug = 7, Sep = 8, Oct = 9, Nov = 10, Dec = 11, } describe('DateMath', () => { it('can add days', () => { const startDate = new Date(2016, Months.Apr, 1); const result = DateMath.addDays(startDate, 5); const expected = new Date(2016, Months.Apr, 6); expect(result.getTime()).toEqual(expected.getTime()); }); it('can add days across a month boundary', () => { const startDate = new Date(2016, Months.Mar, 30); const result = DateMath.addDays(startDate, 5); const expected = new Date(2016, Months.Apr, 4); expect(result.getTime()).toEqual(expected.getTime()); }); it('can add days across multiple month boundaries', () => { const startDate = new Date(2016, Months.Mar, 31); const result = DateMath.addDays(startDate, 65); const expected = new Date(2016, Months.Jun, 4); expect(result.getTime()).toEqual(expected.getTime()); }); it('can add days across leap day boundaries', () => { const startDate = new Date(2016, Months.Feb, 28); const result = DateMath.addDays(startDate, 2); const expected = new Date(2016, Months.Mar, 1); expect(result.getTime()).toEqual(expected.getTime()); }); it('can add months', () => { const startDate = new Date(2015, Months.Dec, 31); let result = DateMath.addMonths(startDate, 1); let expected = new Date(2016, Months.Jan, 31); expect(result.getTime()).toEqual(expected.getTime()); result = DateMath.addMonths(startDate, 2); expected = new Date(2016, Months.Feb, 29); expect(result.getTime()).toEqual(expected.getTime()); result = DateMath.addMonths(startDate, 3); expected = new Date(2016, Months.Mar, 31); expect(result.getTime()).toEqual(expected.getTime()); result = DateMath.addMonths(startDate, 4); expected = new Date(2016, Months.Apr, 30); expect(result.getTime()).toEqual(expected.getTime()); result = DateMath.addMonths(startDate, 5); expected = new Date(2016, Months.May, 31); expect(result.getTime()).toEqual(expected.getTime()); result = DateMath.addMonths(startDate, 6); expected = new Date(2016, Months.Jun, 30); expect(result.getTime()).toEqual(expected.getTime()); result = DateMath.addMonths(startDate, 7); expected = new Date(2016, Months.Jul, 31); expect(result.getTime()).toEqual(expected.getTime()); result = DateMath.addMonths(startDate, 8); expected = new Date(2016, Months.Aug, 31); expect(result.getTime()).toEqual(expected.getTime()); result = DateMath.addMonths(startDate, 9); expected = new Date(2016, Months.Sep, 30); expect(result.getTime()).toEqual(expected.getTime()); result = DateMath.addMonths(startDate, 10); expected = new Date(2016, Months.Oct, 31); expect(result.getTime()).toEqual(expected.getTime()); result = DateMath.addMonths(startDate, 11); expected = new Date(2016, Months.Nov, 30); expect(result.getTime()).toEqual(expected.getTime()); result = DateMath.addMonths(startDate, 12); expected = new Date(2016, Months.Dec, 31); expect(result.getTime()).toEqual(expected.getTime()); result = DateMath.addMonths(startDate, 14); expected = new Date(2017, Months.Feb, 28); expect(result.getTime()).toEqual(expected.getTime()); }); it('can add years', () => { let startDate = new Date(2016, Months.Feb, 29); let result = DateMath.addYears(startDate, 1); let expected = new Date(2017, Months.Feb, 28); expect(result.getTime()).toEqual(expected.getTime()); startDate = new Date(2016, Months.Feb, 29); result = DateMath.addYears(startDate, 4); expected = new Date(2020, Months.Feb, 29); expect(result.getTime()).toEqual(expected.getTime()); startDate = new Date(2016, Months.Jan, 1); result = DateMath.addYears(startDate, 1); expected = new Date(2017, Months.Jan, 1); expect(result.getTime()).toEqual(expected.getTime()); }); it('can subtract days', () => { const startDate = new Date(2016, Months.Apr, 30); const result = DateMath.addDays(startDate, -5); const expected = new Date(2016, Months.Apr, 25); expect(result.getTime()).toEqual(expected.getTime()); }); it('can subtract days across a month boundry', () => { const startDate = new Date(2016, Months.Apr, 1); const result = DateMath.addDays(startDate, -5); const expected = new Date(2016, Months.Mar, 27); expect(result.getTime()).toEqual(expected.getTime()); }); it('can subtract days across multiple month boundaries', () => { const startDate = new Date(2016, Months.Jul, 4); const result = DateMath.addDays(startDate, -65); const expected = new Date(2016, Months.Apr, 30); expect(result.getTime()).toEqual(expected.getTime()); }); it('can subtract days across leap day boundaries', () => { const startDate = new Date(2016, Months.Mar, 1); const result = DateMath.addDays(startDate, -2); const expected = new Date(2016, Months.Feb, 28); expect(result.getTime()).toEqual(expected.getTime()); }); it('can subtract months', () => { const startDate = new Date(2016, Months.Dec, 31); let result = DateMath.addMonths(startDate, -12); let expected = new Date(2015, Months.Dec, 31); expect(result.getTime()).toEqual(expected.getTime()); result = DateMath.addMonths(startDate, -11); expected = new Date(2016, Months.Jan, 31); expect(result.getTime()).toEqual(expected.getTime()); result = DateMath.addMonths(startDate, -10); expected = new Date(2016, Months.Feb, 29); expect(result.getTime()).toEqual(expected.getTime()); result = DateMath.addMonths(startDate, -9); expected = new Date(2016, Months.Mar, 31); expect(result.getTime()).toEqual(expected.getTime()); result = DateMath.addMonths(startDate, -8); expected = new Date(2016, Months.Apr, 30); expect(result.getTime()).toEqual(expected.getTime()); result = DateMath.addMonths(startDate, -7); expected = new Date(2016, Months.May, 31); expect(result.getTime()).toEqual(expected.getTime()); result = DateMath.addMonths(startDate, -6); expected = new Date(2016, Months.Jun, 30); expect(result.getTime()).toEqual(expected.getTime()); result = DateMath.addMonths(startDate, -5); expected = new Date(2016, Months.Jul, 31); expect(result.getTime()).toEqual(expected.getTime()); result = DateMath.addMonths(startDate, -4); expected = new Date(2016, Months.Aug, 31); expect(result.getTime()).toEqual(expected.getTime()); result = DateMath.addMonths(startDate, -3); expected = new Date(2016, Months.Sep, 30); expect(result.getTime()).toEqual(expected.getTime()); result = DateMath.addMonths(startDate, -2); expected = new Date(2016, Months.Oct, 31); expect(result.getTime()).toEqual(expected.getTime()); result = DateMath.addMonths(startDate, -1); expected = new Date(2016, Months.Nov, 30); expect(result.getTime()).toEqual(expected.getTime()); result = DateMath.addMonths(startDate, -22); expected = new Date(2015, Months.Feb, 28); expect(result.getTime()).toEqual(expected.getTime()); }); it('can subtract years', () => { let startDate = new Date(2016, Months.Feb, 29); let result = DateMath.addYears(startDate, -1); let expected = new Date(2015, Months.Feb, 28); expect(result.getTime()).toEqual(expected.getTime()); startDate = new Date(2016, Months.Feb, 29); result = DateMath.addYears(startDate, -4); expected = new Date(2012, Months.Feb, 29); expect(result.getTime()).toEqual(expected.getTime()); startDate = new Date(2016, Months.Jan, 1); result = DateMath.addYears(startDate, -1); expected = new Date(2015, Months.Jan, 1); expect(result.getTime()).toEqual(expected.getTime()); }); it('can set the month', () => { let startDate = new Date(2016, Months.Jan, 31); let result = DateMath.setMonth(startDate, Months.Feb); let expected = new Date(2016, Months.Feb, 29); expect(result.getTime()).toEqual(expected.getTime()); startDate = new Date(2016, Months.Jun, 1); result = DateMath.setMonth(startDate, Months.Feb); expected = new Date(2016, Months.Feb, 1); expect(result.getTime()).toEqual(expected.getTime()); }); it('can compare dates', () => { let date1 = new Date(2016, 4, 1); let date2 = new Date(2016, 4, 1); expect(DateMath.compareDates(date1, date2)).toBe(true); date1 = new Date(2016, 4, 1, 12, 30, 0); date2 = new Date(2016, 4, 1, 10, 0, 0); expect(DateMath.compareDates(date1, date2)).toBe(true); date1 = new Date(2016, 4, 1); date2 = new Date(2016, 4, 2); expect(DateMath.compareDates(date1, date2)).toBe(false); date1 = new Date(2016, 4, 1); date2 = new Date(2016, 5, 1); expect(DateMath.compareDates(date1, date2)).toBe(false); date1 = new Date(2016, 4, 1); date2 = new Date(2017, 4, 1); expect(DateMath.compareDates(date1, date2)).toBe(false); }); it('can get date range array', () => { const date = new Date(2017, 2, 16); // Date range: day let dateRangeArray = DateMath.getDateRangeArray(date, DateRangeType.Day, DayOfWeek.Sunday); expect(dateRangeArray.length).toEqual(1); expect(DateMath.compareDates(dateRangeArray[0], date)).toBe(true); // Date range: week let expectedDates = Array(7).map((val: undefined, i: number) => new Date(2017, 2, 12 + i)); dateRangeArray = DateMath.getDateRangeArray(date, DateRangeType.Week, DayOfWeek.Sunday); Array(7).forEach((val: undefined, i: number) => expect(DateMath.compareDates(dateRangeArray[i], expectedDates[i])).toBe(true), ); // Date range: work week const workWeekDays = [DayOfWeek.Monday, DayOfWeek.Tuesday, DayOfWeek.Thursday, DayOfWeek.Friday]; expectedDates = [new Date(2017, 2, 13), new Date(2017, 2, 14), new Date(2017, 2, 16), new Date(2017, 2, 17)]; dateRangeArray = DateMath.getDateRangeArray(date, DateRangeType.Week, DayOfWeek.Sunday, workWeekDays); Array(4).forEach((val: undefined, i: number) => expect(DateMath.compareDates(dateRangeArray[i], expectedDates[i])).toBe(true), ); // work week defaults expectedDates = [ new Date(2017, 2, 13), new Date(2017, 2, 14), new Date(2017, 2, 15), new Date(2017, 2, 16), new Date(2017, 2, 17), ]; dateRangeArray = DateMath.getDateRangeArray(date, DateRangeType.Week, DayOfWeek.Sunday); Array(4).forEach((val: undefined, i: number) => expect(DateMath.compareDates(dateRangeArray[i], expectedDates[i])).toBe(true), ); // Date range: month expectedDates = Array(31).map((val: undefined, i: number) => new Date(2017, 2, 1 + i)); dateRangeArray = DateMath.getDateRangeArray(date, DateRangeType.Month, DayOfWeek.Sunday); Array(31).forEach((val: undefined, i: number) => expect(DateMath.compareDates(dateRangeArray[i], expectedDates[i])).toBe(true), ); // First day of week: Tuesday expectedDates = Array(7).map((val: undefined, i: number) => new Date(2017, 2, 14 + i)); dateRangeArray = DateMath.getDateRangeArray(date, DateRangeType.Week, DayOfWeek.Tuesday); Array(7).forEach((val: undefined, i: number) => expect(DateMath.compareDates(dateRangeArray[i], date)).toBe(true)); }); // Generating week numbers array per month it('can calculate week numbers from selected date', () => { // firstDayOfWeek is Monday, firstWeekOfYear is firstFullWeek let date = new Date(2017, 0, 4); let result = DateMath.getWeekNumbersInMonth(6, 1, 1, date); let expected = 52; expect(result[0]).toEqual(expected); // firstDayOfWeek is Sunday, firstWeekOfYear is firstFullWeek date = new Date(2000, 11, 31); result = DateMath.getWeekNumbersInMonth(6, 0, 1, date); expected = 53; expect(result[5]).toEqual(expected); // firstDayOfWeek is Sunday, firstWeekOfYear is firstFullWeek date = new Date(2010, 0, 1); result = DateMath.getWeekNumbersInMonth(6, 0, 1, date); expected = 52; expect(result[0]).toEqual(expected); // firstDayOfWeek is Sunday, firstWeekOfYear is firstFourDayWeek date = new Date(2018, 11, 31); result = DateMath.getWeekNumbersInMonth(6, 0, 2, date); expected = 1; expect(result[5]).toEqual(expected); }); // First week of year set to FirstWeekOfYear.FirstDay it('can calculate week numbers - option 0', () => { // firstDayOfWeek is Sunday let date1 = new Date(2018, 0, 1); let result = DateMath.getWeekNumber(date1, 0, 0); let expected = 1; expect(result).toEqual(expected); // firstDayOfWeek is Sunday date1 = new Date(2010, 0, 1); result = DateMath.getWeekNumber(date1, 0, 0); expected = 1; expect(result).toEqual(expected); // firstDayOfWeek is Sunday date1 = new Date(2019, 0, 1); result = DateMath.getWeekNumber(date1, 0, 0); expected = 1; expect(result).toEqual(expected); // firstDayOfWeek is Monday date1 = new Date(2010, 11, 31); result = DateMath.getWeekNumber(date1, 1, 0); expected = 53; expect(result).toEqual(expected); }); // First week of year set to FirstWeekOfYear.FirstFullWeek it('can calculate week numbers - option 1', () => { // firstDayOfWeek is Sunday let date1 = new Date(2018, 0, 1); let result = DateMath.getWeekNumber(date1, 0, 1); let expected = 53; expect(result).toEqual(expected); // firstDayOfWeek is Sunday date1 = new Date(2017, 11, 31); result = DateMath.getWeekNumber(date1, 0, 1); expected = 53; expect(result).toEqual(expected); // firstDayOfWeek is Sunday date1 = new Date(2010, 11, 31); result = DateMath.getWeekNumber(date1, 0, 1); expected = 52; expect(result).toEqual(expected); // firstDayOfWeek is Monday date1 = new Date(2011, 0, 1); result = DateMath.getWeekNumber(date1, 1, 1); expected = 52; expect(result).toEqual(expected); // firstDayOfWeek is Sunday date1 = new Date(2021, 0, 1); result = DateMath.getWeekNumber(date1, 0, 1); expected = 52; expect(result).toEqual(expected); // firstDayOfWeek is Monday date1 = new Date(2021, 0, 1); result = DateMath.getWeekNumber(date1, 1, 1); expected = 52; expect(result).toEqual(expected); }); // First week of year set to FirstWeekOfYear.FirstFourDayWeek it('can calculate week numbers - option 2', () => { // firstDayOfWeek is Sunday let date1 = new Date(2019, 0, 5); let result = DateMath.getWeekNumber(date1, 0, 2); let expected = 1; expect(result).toEqual(expected); // firstDayOfWeek is Sunday date1 = new Date(2018, 0, 6); result = DateMath.getWeekNumber(date1, 0, 2); expected = 1; expect(result).toEqual(expected); // firstDayOfWeek is Sunday date1 = new Date(2014, 11, 31); result = DateMath.getWeekNumber(date1, 0, 2); expected = 53; expect(result).toEqual(expected); // firstDayOfWeek is Sunday date1 = new Date(2015, 0, 1); result = DateMath.getWeekNumber(date1, 0, 2); expected = 53; expect(result).toEqual(expected); // firstDayOfWeek is Sunday date1 = new Date(2010, 11, 31); result = DateMath.getWeekNumber(date1, 0, 2); expected = 52; expect(result).toEqual(expected); // firstDayOfWeek is Monday date1 = new Date(2011, 0, 1); result = DateMath.getWeekNumber(date1, 1, 2); expected = 52; expect(result).toEqual(expected); // firstDayOfWeek is Sunday date1 = new Date(2021, 0, 1); result = DateMath.getWeekNumber(date1, 0, 2); expected = 53; expect(result).toEqual(expected); // firstDayOfWeek is Monday date1 = new Date(2021, 0, 1); result = DateMath.getWeekNumber(date1, 1, 2); expected = 53; expect(result).toEqual(expected); }); it('can get the month start and end', () => { const date = new Date('Dec 15 2017'); // First day of month expect(DateMath.compareDates(new Date('Dec 1 2017'), DateMath.getMonthStart(date))).toBe(true); // Last day of month expect(DateMath.compareDates(new Date('Dec 31 2017'), DateMath.getMonthEnd(date))).toBe(true); }); it('can get the year start and end', () => { const date = new Date('Dec 15 2017'); // First day of year expect(DateMath.compareDates(new Date('Jan 1 2017'), DateMath.getYearStart(date))).toBe(true); // Last day of year expect(DateMath.compareDates(new Date('Dec 31 2017'), DateMath.getYearEnd(date))).toBe(true); }); it('can get start date of week', () => { const date = new Date('Aug 2 2020'); expect(DateMath.compareDates(new Date('Jul 28 2020'), DateMath.getStartDateOfWeek(date, DayOfWeek.Tuesday))).toBe( true, ); }); it('can get end date of week', () => { const date = new Date('Sep 29 2020'); expect(DateMath.compareDates(new Date('Oct 5 2020'), DateMath.getEndDateOfWeek(date, DayOfWeek.Tuesday))).toBe( true, ); }); });
8,105
0
petrpan-code/microsoft/fluentui/packages/date-time-utilities/src
petrpan-code/microsoft/fluentui/packages/date-time-utilities/src/timeFormatting/timeFormatting.test.ts
import { formatTimeString } from '.'; describe('timeFormatting', () => { const date = new Date(2021, 6, 14, 13, 26, 39); const originalToLocaleTimeString = date.toLocaleTimeString.bind(date); /** * * This is needed to make this test pass in any time-zone as the implementation defines no locales, * thus it will be determined on users physical location - making the test non-deterministic * */ const toLocaleTimeStringMock: (locales?: string | string[], options?: Intl.DateTimeFormatOptions) => string = ( locales, options, ) => { if (!locales || (Array.isArray(locales) && locales.length === 0)) { return originalToLocaleTimeString('en-US', options); } // this branch will never run as the implementation uses `[]` for locales. // keeping it here to follow best testing/mocking practices return originalToLocaleTimeString(locales, options); }; jest.spyOn(date, 'toLocaleTimeString').mockImplementation(toLocaleTimeStringMock); afterAll(() => { jest.resetAllMocks(); }); it('returns locale time string', () => { const result = formatTimeString(date); expect(result).toBe('1:26 PM'); }); it('returns locale time string with seconds', () => { const result = formatTimeString(date, true); expect(result).toBe('1:26:39 PM'); }); it('returns locale time string with 12-hour time', () => { const result = formatTimeString(date, false, true); expect(result).toBe('1:26 PM'); }); it('returns locale time string with 24-hour time', () => { const result = formatTimeString(date, false, false); expect(result).toBe('13:26'); }); it('returns locale time string with seconds and 12-hour time', () => { const result = formatTimeString(date, true, true); expect(result).toBe('1:26:39 PM'); }); it('returns locale time string with seconds and 24-hour time', () => { const result = formatTimeString(date, true, false); expect(result).toBe('13:26:39'); }); });
8,106
0
petrpan-code/microsoft/fluentui/packages/date-time-utilities/src
petrpan-code/microsoft/fluentui/packages/date-time-utilities/src/timeMath/timeMath.test.ts
import * as TimeMath from './timeMath'; describe('timeMath', () => { it('can add minutes', () => { let startDate; let result; startDate = new Date(2015, 3, 31); result = TimeMath.addMinutes(startDate, 30); expect(result.getMinutes()).toBe(30); startDate = new Date(2021, 6, 14, 5, 9, 21); result = TimeMath.addMinutes(startDate, 30); expect(result.getMinutes()).toBe(39); startDate = new Date(2021, 6, 14, 5, 30, 21); result = TimeMath.addMinutes(startDate, 30); expect(result.getMinutes()).toBe(0); startDate = new Date(2021, 6, 14, 5, 46, 21); result = TimeMath.addMinutes(startDate, 35); expect(result.getMinutes()).toBe(21); startDate = new Date(2021, 6, 14, 5, 46, 21); result = TimeMath.addMinutes(startDate, 126); expect(result.getMinutes()).toBe(52); startDate = new Date(2021, 6, 14, 5, 46, 21); result = TimeMath.addMinutes(startDate, 0); expect(result.getMinutes()).toBe(46); startDate = new Date(2021, 6, 14, 5, 46, 21); result = TimeMath.addMinutes(startDate, -30); expect(result.getMinutes()).toBe(16); startDate = new Date(2021, 6, 14, 5, 24, 21); result = TimeMath.addMinutes(startDate, -48); expect(result.getMinutes()).toBe(36); startDate = new Date(2021, 6, 14, 5, 24, 21); result = TimeMath.addMinutes(startDate, -97); expect(result.getMinutes()).toBe(47); }); it('can ceil minute', () => { const date = new Date(); let result: Date; date.setMinutes(5); result = TimeMath.ceilMinuteToIncrement(date, 15); expect(result.getMinutes()).toBe(15); date.setMinutes(0); result = TimeMath.ceilMinuteToIncrement(date, 15); expect(result.getMinutes()).toBe(0); result = TimeMath.ceilMinuteToIncrement(date, 44); expect(result.getMinutes()).toBe(0); date.setMinutes(32); result = TimeMath.ceilMinuteToIncrement(date, 15); expect(result.getMinutes()).toBe(45); date.setMinutes(15); result = TimeMath.ceilMinuteToIncrement(date, 30); expect(result.getMinutes()).toBe(30); date.setMinutes(15); result = TimeMath.ceilMinuteToIncrement(date, 60); expect(result.getMinutes()).toBe(0); }); it('can get date from time selection', () => { const baseDate = new Date('November 25, 2021 09:15:00'); let result: Date; result = TimeMath.getDateFromTimeSelection(false, baseDate, '11:30'); expect(result.getMonth()).toBe(10); expect(result.getDate()).toBe(25); expect(result.getHours()).toBe(11); expect(result.getMinutes()).toBe(30); result = TimeMath.getDateFromTimeSelection(true, baseDate, '12:00 am'); expect(result.getMonth()).toBe(10); expect(result.getDate()).toBe(26); expect(result.getHours()).toBe(0); expect(result.getMinutes()).toBe(0); result = TimeMath.getDateFromTimeSelection(false, baseDate, '7:00:00'); expect(result.getMonth()).toBe(10); expect(result.getDate()).toBe(26); expect(result.getHours()).toBe(7); expect(result.getMinutes()).toBe(0); result = TimeMath.getDateFromTimeSelection(true, baseDate, '4:20 PM'); expect(result.getMonth()).toBe(10); expect(result.getDate()).toBe(25); expect(result.getHours()).toBe(16); expect(result.getMinutes()).toBe(20); result = TimeMath.getDateFromTimeSelection(false, baseDate, '9:15'); expect(result.getMonth()).toBe(10); expect(result.getDate()).toBe(25); expect(result.getHours()).toBe(9); expect(result.getMinutes()).toBe(15); result = TimeMath.getDateFromTimeSelection(true, baseDate, '9:00 am'); expect(result.getMonth()).toBe(10); expect(result.getDate()).toBe(26); expect(result.getHours()).toBe(9); expect(result.getMinutes()).toBe(0); }); it('can get date from time selection over New Years', () => { const baseDate = new Date('December 31, 2021 08:00:00'); let result: Date; result = TimeMath.getDateFromTimeSelection(false, baseDate, '00:00'); expect(result.getMonth()).toBe(0); expect(result.getDate()).toBe(1); expect(result.getHours()).toBe(0); expect(result.getMinutes()).toBe(0); result = TimeMath.getDateFromTimeSelection(true, baseDate, '11:59 pm'); expect(result.getMonth()).toBe(11); expect(result.getDate()).toBe(31); expect(result.getHours()).toBe(23); expect(result.getMinutes()).toBe(59); result = TimeMath.getDateFromTimeSelection(false, baseDate, '07:59'); expect(result.getMonth()).toBe(0); expect(result.getDate()).toBe(1); expect(result.getHours()).toBe(7); expect(result.getMinutes()).toBe(59); result = TimeMath.getDateFromTimeSelection(true, baseDate, '1:30 pm'); expect(result.getMonth()).toBe(11); expect(result.getDate()).toBe(31); expect(result.getHours()).toBe(13); expect(result.getMinutes()).toBe(30); }); });
8,128
0
petrpan-code/microsoft/fluentui/packages/dom-utilities
petrpan-code/microsoft/fluentui/packages/dom-utilities/src/index.test.ts
import { portalContainsElement } from './portalContainsElement'; import { DATA_PORTAL_ATTRIBUTE, setPortalAttribute } from './setPortalAttribute'; import { elementContains } from './elementContains'; import { getParent } from './getParent'; const unattachedSvg = document.createElement('svg'); const unattachedDiv = document.createElement('div'); const parentDiv = document.createElement('div'); const childDiv = document.createElement('div'); parentDiv.appendChild(childDiv); describe('elementContains', () => { it('can find a child', () => { expect(elementContains(parentDiv, childDiv)).toEqual(true); }); it('can find itself', () => { expect(elementContains(childDiv, childDiv)).toEqual(true); expect(elementContains(childDiv, childDiv, false)).toEqual(true); }); it('can return false on an unattached child', () => { expect(elementContains(parentDiv, unattachedDiv)).toEqual(false); }); it('can return false on a null child', () => { expect(elementContains(parentDiv, null)).toEqual(false); }); it('can return false on a null parent', () => { expect(elementContains(null, null)).toEqual(false); }); it('can return false when parent is an svg', () => { expect(elementContains(unattachedSvg, unattachedDiv)).toEqual(false); }); }); describe('getParent', () => { it('returns correct parent for inner SVG elements', () => { const childSvg = document.createElement('svg'); const svgRectangle = document.createElement('rect'); childSvg.appendChild(svgRectangle); parentDiv.appendChild(childSvg); expect(getParent(svgRectangle)).toEqual(childSvg); expect(getParent(childSvg)).toEqual(parentDiv); }); }); describe('setPortalAttribute', () => { it('sets attribute', () => { const testDiv = document.createElement('div'); expect(testDiv.getAttribute(DATA_PORTAL_ATTRIBUTE)).toBeFalsy(); setPortalAttribute(testDiv); expect(testDiv.getAttribute(DATA_PORTAL_ATTRIBUTE)).toBeTruthy(); }); }); describe('portalContainsElement', () => { let root: HTMLElement; let leaf: HTMLElement; let parent: HTMLElement; let portal: HTMLElement; let unlinked: HTMLElement; beforeEach(() => { root = document.createElement('div'); leaf = document.createElement('div'); parent = document.createElement('div'); portal = document.createElement('div'); unlinked = document.createElement('div'); setPortalAttribute(portal); }); it('works with and without parent specified', () => { root.appendChild(parent); parent.appendChild(portal); portal.appendChild(leaf); expect(portalContainsElement(root)).toBeFalsy(); expect(portalContainsElement(parent)).toBeFalsy(); expect(portalContainsElement(portal)).toBeTruthy(); expect(portalContainsElement(leaf)).toBeTruthy(); expect(portalContainsElement(leaf, parent)).toBeTruthy(); }); it('works correctly when parent and child are in same portal', () => { root.appendChild(portal); portal.appendChild(parent); parent.appendChild(leaf); expect(portalContainsElement(parent)).toBeTruthy(); expect(portalContainsElement(leaf, parent)).toBeFalsy(); }); it('works with hierarchically invalid parents', () => { root.appendChild(parent); parent.appendChild(portal); portal.appendChild(leaf); // When parent is invalid, searches should go to root expect(portalContainsElement(root, leaf)).toBeFalsy(); expect(portalContainsElement(parent, leaf)).toBeFalsy(); expect(portalContainsElement(portal, leaf)).toBeTruthy(); expect(portalContainsElement(leaf, unlinked)).toBeTruthy(); }); it('works when element is parent', () => { root.appendChild(parent); parent.appendChild(portal); portal.appendChild(leaf); expect(portalContainsElement(root, root)).toBeFalsy(); expect(portalContainsElement(parent, parent)).toBeFalsy(); expect(portalContainsElement(portal, portal)).toBeTruthy(); expect(portalContainsElement(leaf, leaf)).toBeFalsy(); }); });
8,390
0
petrpan-code/microsoft/fluentui/packages/fluentui/accessibility/src
petrpan-code/microsoft/fluentui/packages/fluentui/accessibility/src/keyboard-key/index.test.ts
import { codes } from './codes'; import { getCode, getKey, keyboardKey } from './index'; /* eslint-disable @typescript-eslint/no-explicit-any */ describe('keyboardKey', () => { it('has a key/value for every value/key in codes', () => { Object.keys(codes).forEach(code => { const name = codes[Number(code)]; if (Array.isArray(name)) { expect(String((keyboardKey as any)[name[0]])).toEqual(code); expect(String((keyboardKey as any)[name[1]])).toEqual(code); } else { expect(String((keyboardKey as any)[name])).toEqual(code); } }); }); describe('getCode', () => { it('is a function', () => { expect(getCode).toBeInstanceOf(Function); }); it('returns the code for a given key name', () => { expect(getCode('Enter')).toEqual(13); }); it('handles all key names in codes', () => { Object.keys(codes).forEach(code => { const name = codes[code]; const _code = Number(code); if (Array.isArray(name)) { expect(getCode(name[0])).toEqual(_code); expect(getCode(name[1])).toEqual(_code); } else { expect(getCode(name)).toEqual(_code); } }); }); it('handles event like objects with `key` prop', () => { Object.keys(codes).forEach(code => { const name = codes[code]; const _code = Number(code); if (Array.isArray(name)) { const key0 = { key: name[0], which: _code, keyCode: _code, shiftKey: false }; const key1 = { key: name[1], which: _code, keyCode: _code, shiftKey: false }; expect(getCode(key0)).toEqual(_code); expect(getCode(key1)).toEqual(_code); } else { const key = { key: name, which: _code, keyCode: _code, shiftKey: false }; expect(getCode(key)).toEqual(_code); } }); }); }); describe('getKey', () => { it('is a function', () => { expect(getKey).toBeInstanceOf(Function); }); it('returns the code for a given key name', () => { expect(getKey(13)).toEqual('Enter'); }); it('handles all codes', () => { Object.keys(codes).forEach(code => { const name = codes[code]; const keyName = getKey(Number(code)); if (Array.isArray(name)) { expect(keyName).toEqual(name[0]); } else { expect(keyName).toEqual(name); } }); }); it('handles event like object: { keyCode: code, shiftKey: false }`', () => { Object.keys(codes).forEach(code => { const name = codes[code]; const _code = Number(code); const keyName = getKey({ which: _code, keyCode: _code, shiftKey: false }); if (Array.isArray(name)) { expect(keyName).toEqual(name[0]); } else { expect(keyName).toEqual(name); } }); }); it('handles event like object: { keyCode: code, shiftKey: true }`', () => { Object.keys(codes).forEach(code => { const name = codes[code]; const keyName = getKey({ keyCode: Number(code), shiftKey: true }); if (Array.isArray(name)) { expect(keyName).toEqual(name[1]); } else { expect(keyName).toEqual(name); } }); }); it('handles event like object: { which: code, shiftKey: false }', () => { Object.keys(codes).forEach(code => { const name = codes[code]; const keyName = getKey({ which: Number(code), shiftKey: false }); if (Array.isArray(name)) { expect(keyName).toEqual(name[0]); } else { expect(keyName).toEqual(name); } }); }); it('handles event like object: { which: code, shiftKey: true }', () => { Object.keys(codes).forEach(code => { const name = codes[code]; const keyName = getKey({ which: Number(code), shiftKey: true }); if (Array.isArray(name)) { expect(keyName).toEqual(name[1]); } else { expect(keyName).toEqual(name); } }); }); it('handles event like objects with a `key` property', () => { const keyName = getKey({ key: '/' }); expect(keyName).toEqual('/'); }); }); });
8,392
0
petrpan-code/microsoft/fluentui/packages/fluentui/accessibility/test
petrpan-code/microsoft/fluentui/packages/fluentui/accessibility/test/behaviors/accordionTitleBehavior-test.tsx
import { accordionTitleBehavior } from '@fluentui/accessibility'; describe('AccordionTitleBehavior.ts', () => { test('adds role and aria-level attribute if as prop is not a heading', () => { for (let index = 1; index <= 6; index++) { const expectedResult = accordionTitleBehavior({ as: `h${index}` }); expect(expectedResult.attributes.root.role).toBeUndefined(); expect(expectedResult.attributes.root['aria-level']).toBeUndefined(); } }); test('adds role and aria-level attribute if as prop is not a heading', () => { const expectedResult = accordionTitleBehavior({ as: 'div' }); expect(expectedResult.attributes.root.role).toEqual('heading'); expect(expectedResult.attributes.root['aria-level']).toEqual(3); }); test('adds aria-disabled="true" attribute if active="true" and canBeCollapsed="false"', () => { const expectedResult = accordionTitleBehavior({ active: true, canBeCollapsed: false }); expect(expectedResult.attributes.content['aria-disabled']).toEqual(true); }); test('adds aria-disabled="false" attribute if active="true" and canBeCollapsed="true"', () => { const expectedResult = accordionTitleBehavior({ active: true, canBeCollapsed: true }); expect(expectedResult.attributes.content['aria-disabled']).toEqual(false); }); test('adds aria-disabled="false" attribute if active="false"', () => { const expectedResult = accordionTitleBehavior({ active: false }); expect(expectedResult.attributes.content['aria-disabled']).toEqual(false); }); });
8,393
0
petrpan-code/microsoft/fluentui/packages/fluentui/accessibility/test
petrpan-code/microsoft/fluentui/packages/fluentui/accessibility/test/behaviors/alertBehavior-test.tsx
import { alertBehavior } from '@fluentui/accessibility'; describe('AlertBehavior.ts', () => { test('use alertWarningBehavior if warning prop is defined', () => { const expectedResult = alertBehavior({ warning: true }); expect(expectedResult.attributes.body.role).toEqual('alert'); }); test('use alertWarningBehavior if danger prop is defined', () => { const expectedResult = alertBehavior({ danger: true }); expect(expectedResult.attributes.body.role).toEqual('alert'); }); test('use aria-describedby if dismiss action is defined for non-warning alert', () => { const expectedResult = alertBehavior({ bodyId: 'alertId' }); expect(expectedResult.attributes.dismissAction['aria-describedby']).toEqual('alertId'); }); test('use aria-describedby if dismiss action is defined for warning alert', () => { const expectedResult = alertBehavior({ warning: true, bodyId: 'alertId' }); expect(expectedResult.attributes.dismissAction['aria-describedby']).toEqual('alertId'); }); });
8,394
0
petrpan-code/microsoft/fluentui/packages/fluentui/accessibility/test
petrpan-code/microsoft/fluentui/packages/fluentui/accessibility/test/behaviors/behavior-test.tsx
// Behavior-test use 'docs\src\behaviorMenu.json' file as source of strings to parse. // The json file is generated by task 'build:docs:component-menu-behaviors'. The task will generate json file from the behaviors description. // If you change behavior description, then you need to run: // - 'gulp build:docs:component-menu-behaviors' in order to get json file generated // OR // - 'yarn test' which has creating json file predefined in "pretest" step import { attachmentBehavior, basicListBehavior, basicListItemBehavior, buttonBehavior, checkboxBehavior, embedBehavior, iconBehavior, imageBehavior, indicatorBehavior, inputBehavior, loaderBehavior, menuBehavior, menuItemBehavior, menuDividerBehavior, submenuBehavior, popupBehavior, dialogBehavior, radioGroupBehavior, radioGroupItemBehavior, navigableListBehavior, navigableListItemBehavior, selectableListBehavior, selectableListItemBehavior, sliderBehavior, tabBehavior, tabListBehavior, toggleButtonBehavior, menuAsToolbarBehavior, menuItemAsToolbarButtonBehavior, gridBehavior, gridHorizontalBehavior, statusBehavior, alertWarningBehavior, alertBaseBehavior, accordionBehavior, accordionTitleBehavior, accordionContentBehavior, chatBehavior, chatMessageBehavior, toolbarBehavior, toolbarItemBehavior, toolbarMenuBehavior, toolbarMenuItemCheckboxBehavior, toolbarMenuItemBehavior, toolbarMenuItemRadioBehavior, toolbarMenuRadioGroupBehavior, toolbarMenuDividerBehavior, toolbarMenuRadioGroupWrapperBehavior, toolbarRadioGroupBehavior, toolbarRadioGroupItemBehavior, tooltipAsDescriptionBehavior, tooltipAsLabelBehavior, menuButtonBehavior, splitButtonBehavior, treeBehavior, treeItemBehavior, treeTitleBehavior, textAreaBehavior, treeAsListBehavior, treeItemAsListItemBehavior, treeTitleAsListItemTitleBehavior, treeAsListboxBehavior, treeItemAsOptionBehavior, treeTitleAsOptionBehavior, carouselItemBehavior, carouselBehavior, tableBehavior, tableCellBehavior, tableHeaderCellBehavior, tableRowBehavior, gridNestedBehavior, gridHeaderRowBehavior, gridHeaderCellBehavior, gridRowNestedBehavior, gridCellBehavior, gridCellMultipleFocusableBehavior, gridCellWithFocusableElementBehavior, cardBehavior, cardFocusableBehavior, cardChildrenFocusableBehavior, cardsContainerBehavior, videoBehavior, buttonGroupBehavior, hiddenComponentBehavior, cardSelectableBehavior, dropdownSelectedItemBehavior, datepickerBehavior, datepickerCalendarBehavior, datepickerCalendarHeaderBehavior, datepickerCalendarGridBehavior, datepickerCalendarGridRowBehavior, datepickerCalendarCellBehavior, datepickerCalendarCellButtonBehavior, breadcrumbBehavior, breadcrumbItemBehavior, breadcrumbDividerBehavior, pillBehavior, pillActionBehavior, } from '@fluentui/accessibility'; import { TestHelper } from './testHelper'; import { definitions } from './testDefinitions'; const behaviorMenuItems = require('../../../docs/src/behaviorMenu'); const testHelper = new TestHelper(); testHelper.addTests(definitions); testHelper.addBehavior('attachmentBehavior', attachmentBehavior); testHelper.addBehavior('basicListBehavior', basicListBehavior); testHelper.addBehavior('basicListItemBehavior', basicListItemBehavior); testHelper.addBehavior('buttonBehavior', buttonBehavior); testHelper.addBehavior('buttonGroupBehavior', buttonGroupBehavior); testHelper.addBehavior('checkboxBehavior', checkboxBehavior); testHelper.addBehavior('embedBehavior', embedBehavior); testHelper.addBehavior('iconBehavior', iconBehavior); testHelper.addBehavior('inputBehavior', inputBehavior); testHelper.addBehavior('imageBehavior', imageBehavior); testHelper.addBehavior('indicatorBehavior', indicatorBehavior); testHelper.addBehavior('loaderBehavior', loaderBehavior); testHelper.addBehavior('menuBehavior', menuBehavior); testHelper.addBehavior('menuItemBehavior', menuItemBehavior); testHelper.addBehavior('menuDividerBehavior', menuDividerBehavior); testHelper.addBehavior('menuButtonBehavior', menuButtonBehavior); testHelper.addBehavior('submenuBehavior', submenuBehavior); testHelper.addBehavior('popupBehavior', popupBehavior); testHelper.addBehavior('radioGroupBehavior', radioGroupBehavior); testHelper.addBehavior('radioGroupItemBehavior', radioGroupItemBehavior); testHelper.addBehavior('navigableListBehavior', navigableListBehavior); testHelper.addBehavior('navigableListItemBehavior', navigableListItemBehavior); testHelper.addBehavior('selectableListBehavior', selectableListBehavior); testHelper.addBehavior('selectableListItemBehavior', selectableListItemBehavior); testHelper.addBehavior('sliderBehavior', sliderBehavior); testHelper.addBehavior('tabBehavior', tabBehavior); testHelper.addBehavior('tabListBehavior', tabListBehavior); testHelper.addBehavior('menuAsToolbarBehavior', menuAsToolbarBehavior); testHelper.addBehavior('toggleButtonBehavior', toggleButtonBehavior); testHelper.addBehavior('menuItemAsToolbarButtonBehavior', menuItemAsToolbarButtonBehavior); testHelper.addBehavior('gridBehavior', gridBehavior); testHelper.addBehavior('gridHorizontalBehavior', gridHorizontalBehavior); testHelper.addBehavior('dialogBehavior', dialogBehavior); testHelper.addBehavior('statusBehavior', statusBehavior); testHelper.addBehavior('alertWarningBehavior', alertWarningBehavior); testHelper.addBehavior('alertBaseBehavior', alertBaseBehavior); testHelper.addBehavior('accordionBehavior', accordionBehavior); testHelper.addBehavior('accordionTitleBehavior', accordionTitleBehavior); testHelper.addBehavior('accordionContentBehavior', accordionContentBehavior); testHelper.addBehavior('chatBehavior', chatBehavior); testHelper.addBehavior('chatMessageBehavior', chatMessageBehavior); testHelper.addBehavior('toolbarBehavior', toolbarBehavior); testHelper.addBehavior('toolbarItemBehavior', toolbarItemBehavior); testHelper.addBehavior('toolbarMenuBehavior', toolbarMenuBehavior); testHelper.addBehavior('toolbarMenuItemBehavior', toolbarMenuItemBehavior); testHelper.addBehavior('toolbarMenuItemCheckboxBehavior', toolbarMenuItemCheckboxBehavior); testHelper.addBehavior('toolbarMenuItemRadioBehavior', toolbarMenuItemRadioBehavior); testHelper.addBehavior('toolbarMenuDividerBehavior', toolbarMenuDividerBehavior); testHelper.addBehavior('toolbarMenuRadioGroupBehavior', toolbarMenuRadioGroupBehavior); testHelper.addBehavior('toolbarMenuRadioGroupWrapperBehavior', toolbarMenuRadioGroupWrapperBehavior); testHelper.addBehavior('toolbarRadioGroupBehavior', toolbarRadioGroupBehavior); testHelper.addBehavior('toolbarRadioGroupItemBehavior', toolbarRadioGroupItemBehavior); testHelper.addBehavior('tooltipAsDescriptionBehavior', tooltipAsDescriptionBehavior); testHelper.addBehavior('tooltipAsLabelBehavior', tooltipAsLabelBehavior); testHelper.addBehavior('splitButtonBehavior', splitButtonBehavior); testHelper.addBehavior('treeBehavior', treeBehavior); testHelper.addBehavior('treeItemBehavior', treeItemBehavior); testHelper.addBehavior('treeTitleBehavior', treeTitleBehavior); testHelper.addBehavior('textAreaBehavior', textAreaBehavior); testHelper.addBehavior('treeAsListBehavior', treeAsListBehavior); testHelper.addBehavior('treeItemAsListItemBehavior', treeItemAsListItemBehavior); testHelper.addBehavior('treeTitleAsListItemTitleBehavior', treeTitleAsListItemTitleBehavior); testHelper.addBehavior('treeAsListboxBehavior', treeAsListboxBehavior); testHelper.addBehavior('treeItemAsOptionBehavior', treeItemAsOptionBehavior); testHelper.addBehavior('treeTitleAsOptionBehavior', treeTitleAsOptionBehavior); testHelper.addBehavior('carouselItemBehavior', carouselItemBehavior); testHelper.addBehavior('carouselBehavior', carouselBehavior); testHelper.addBehavior('tableBehavior', tableBehavior); testHelper.addBehavior('tableCellBehavior', tableCellBehavior); testHelper.addBehavior('tableHeaderCellBehavior', tableHeaderCellBehavior); testHelper.addBehavior('tableRowBehavior', tableRowBehavior); testHelper.addBehavior('gridNestedBehavior', gridNestedBehavior); testHelper.addBehavior('gridHeaderRowBehavior', gridHeaderRowBehavior); testHelper.addBehavior('gridHeaderCellBehavior', gridHeaderCellBehavior); testHelper.addBehavior('gridRowNestedBehavior', gridRowNestedBehavior); testHelper.addBehavior('gridCellBehavior', gridCellBehavior); testHelper.addBehavior('gridCellMultipleFocusableBehavior', gridCellMultipleFocusableBehavior); testHelper.addBehavior('gridCellWithFocusableElementBehavior', gridCellWithFocusableElementBehavior); testHelper.addBehavior('cardBehavior', cardBehavior); testHelper.addBehavior('cardFocusableBehavior', cardFocusableBehavior); testHelper.addBehavior('cardChildrenFocusableBehavior', cardChildrenFocusableBehavior); testHelper.addBehavior('cardsContainerBehavior', cardsContainerBehavior); testHelper.addBehavior('videoBehavior', videoBehavior); testHelper.addBehavior('hiddenComponentBehavior', hiddenComponentBehavior); testHelper.addBehavior('cardSelectableBehavior', cardSelectableBehavior); testHelper.addBehavior('dropdownSelectedItemBehavior', dropdownSelectedItemBehavior); testHelper.addBehavior('datepickerBehavior', datepickerBehavior); testHelper.addBehavior('datepickerCalendarBehavior', datepickerCalendarBehavior); testHelper.addBehavior('datepickerCalendarHeaderBehavior', datepickerCalendarHeaderBehavior); testHelper.addBehavior('datepickerCalendarGridBehavior', datepickerCalendarGridBehavior); testHelper.addBehavior('datepickerCalendarGridRowBehavior', datepickerCalendarGridRowBehavior); testHelper.addBehavior('datepickerCalendarCellBehavior', datepickerCalendarCellBehavior); testHelper.addBehavior('datepickerCalendarCellButtonBehavior', datepickerCalendarCellButtonBehavior); testHelper.addBehavior('breadcrumbBehavior', breadcrumbBehavior); testHelper.addBehavior('breadcrumbItemBehavior', breadcrumbItemBehavior); testHelper.addBehavior('breadcrumbDividerBehavior', breadcrumbDividerBehavior); testHelper.addBehavior('pillBehavior', pillBehavior); testHelper.addBehavior('pillActionBehavior', pillActionBehavior); testHelper.run(behaviorMenuItems);
8,395
0
petrpan-code/microsoft/fluentui/packages/fluentui/accessibility/test
petrpan-code/microsoft/fluentui/packages/fluentui/accessibility/test/behaviors/caroselBehavior-test.tsx
import { carouselBehavior } from '@fluentui/accessibility'; const roleDescription = 'carousel'; const label = 'portrait collection'; // set both props to false, as tests are writen in 'Carousel-test.tsx' file const paddleHiddenProps = { paddlePreviousHidden: false, paddleNextHidden: false, }; describe('carouselBehavior.ts', () => { describe('root', () => { test(`sets "role=region" when carousel has NO navigation`, () => { const expectedResult = carouselBehavior({ ariaLiveOn: false, navigation: false, ...paddleHiddenProps }); expect(expectedResult.attributes.root.role).toEqual('region'); }); test('sets "aria-roledescription" when carousel has NO navigation', () => { const expectedResult = carouselBehavior({ ariaLiveOn: false, navigation: false, 'aria-roledescription': roleDescription, ...paddleHiddenProps, }); expect(expectedResult.attributes.root['aria-roledescription']).toEqual(roleDescription); }); test('sets "aria-label" when carousel has NO navigation', () => { const expectedResult = carouselBehavior({ ariaLiveOn: false, navigation: false, 'aria-label': label, ...paddleHiddenProps, }); expect(expectedResult.attributes.root['aria-label']).toEqual(label); }); test('do NOT set aria atributes and role when carousel has navigation', () => { const expectedResult = carouselBehavior({ ariaLiveOn: false, navigation: true, 'aria-roledescription': roleDescription, 'aria-label': label, ...paddleHiddenProps, }); expect(expectedResult.attributes.root['aria-roledescription']).toBeUndefined(); expect(expectedResult.attributes.root['aria-label']).toBeUndefined(); expect(expectedResult.attributes.root.role).toBeUndefined(); }); }); describe('itemsContainer', () => { test(`sets "role=region" when carousel has navigation`, () => { const expectedResult = carouselBehavior({ ariaLiveOn: false, navigation: true, ...paddleHiddenProps }); expect(expectedResult.attributes.itemsContainer.role).toEqual('region'); }); test('sets "aria-roledescription" when carousel has navigation', () => { const expectedResult = carouselBehavior({ ariaLiveOn: false, navigation: true, 'aria-roledescription': roleDescription, ...paddleHiddenProps, }); expect(expectedResult.attributes.itemsContainer['aria-roledescription']).toEqual(roleDescription); }); test('sets "aria-label" when carousel has navigation', () => { const expectedResult = carouselBehavior({ ariaLiveOn: false, navigation: true, 'aria-label': label, ...paddleHiddenProps, }); expect(expectedResult.attributes.itemsContainer['aria-label']).toEqual(label); }); test('do NOT set aria attributes when carousel has NO navigation', () => { const expectedResult = carouselBehavior({ ariaLiveOn: false, navigation: false, 'aria-roledescription': roleDescription, 'aria-label': label, ...paddleHiddenProps, }); expect(expectedResult.attributes.itemsContainer['aria-roledescription']).toBeUndefined(); expect(expectedResult.attributes.itemsContainer['aria-label']).toBeUndefined(); }); test(`sets "role=none" when carousel has NO navigation`, () => { const expectedResult = carouselBehavior({ ariaLiveOn: false, navigation: false, ...paddleHiddenProps }); expect(expectedResult.attributes.itemsContainer.role).toEqual('none'); }); test(`sets "tabindex=-1" when carousel has NO navigation`, () => { const expectedResult = carouselBehavior({ ariaLiveOn: false, navigation: false, ...paddleHiddenProps }); expect(expectedResult.attributes.itemsContainer.tabIndex).toEqual(-1); }); }); });