level_0
int64
0
10k
index
int64
0
0
repo_id
stringlengths
22
152
file_path
stringlengths
41
203
content
stringlengths
11
11.5M
4,516
0
petrpan-code/redwoodjs/redwood/packages/cli-helpers/src/auth
petrpan-code/redwoodjs/redwood/packages/cli-helpers/src/auth/__tests__/authFiles.test.ts
// Have to use `var` here to avoid "Temporal Dead Zone" issues let mockBasePath = '' let mockIsTypeScriptProject = true globalThis.__dirname = __dirname jest.mock('../../lib/paths', () => { const path = require('path') return { ...jest.requireActual('../../lib/paths'), getPaths: () => { const base = mockBasePath || '/mock/base/path' return { api: { src: path.join(base, 'api', 'src'), functions: path.join(base, 'api', 'src', 'functions'), lib: path.join(base, 'api', 'src', 'lib'), }, } }, } }) jest.mock('../../lib/project', () => ({ isTypeScriptProject: () => mockIsTypeScriptProject, })) import path from 'path' import { getPaths } from '../../lib/paths' import { apiSideFiles, generateUniqueFileNames } from '../authFiles' beforeEach(() => { mockIsTypeScriptProject = true }) it('generates a record of TS files', () => { const filePaths = Object.keys( apiSideFiles({ basedir: path.join(__dirname, 'fixtures/supertokensSetup'), webAuthn: false, }) ).sort() expect(filePaths).toEqual([ path.join(getPaths().api.functions, 'auth.ts'), path.join(getPaths().api.lib, 'auth.ts'), path.join(getPaths().api.lib, 'supertokens.ts'), ]) }) it('generates a record of JS files', () => { mockIsTypeScriptProject = false const filePaths = Object.keys( apiSideFiles({ basedir: path.join(__dirname, 'fixtures/supertokensSetup'), webAuthn: false, }) ).sort() expect(filePaths).toEqual([ path.join(getPaths().api.functions, 'auth.js'), path.join(getPaths().api.lib, 'auth.js'), path.join(getPaths().api.lib, 'supertokens.js'), ]) }) it('generates a record of webAuthn files', () => { const filesRecord = apiSideFiles({ basedir: path.join(__dirname, 'fixtures/dbAuthSetup'), webAuthn: true, }) expect(Object.keys(filesRecord)).toHaveLength(2) expect( Object.values(filesRecord).some((content) => content.toLowerCase().includes('webauthn') ) ).toBeTruthy() expect( Object.values(filesRecord).some( (content) => !content.toLowerCase().includes('webauthn') ) ).toBeTruthy() }) it('generates new filenames to avoid overwriting existing files', () => { mockBasePath = path.join(__dirname, 'fixtures', 'app') const conflictingFilesRecord = { [path.join(mockBasePath, 'api', 'src', 'functions', 'auth.ts')]: 'functions/auth.ts file content', [path.join(mockBasePath, 'api', 'src', 'lib', 'auth.ts')]: 'lib/auth.ts file content', [path.join(mockBasePath, 'api', 'src', 'lib', 'supertokens.ts')]: 'lib/supertokens.ts file content', } const filesRecord = generateUniqueFileNames( conflictingFilesRecord, 'supertokens' ) const filePaths = Object.keys(filesRecord).sort() expect(filePaths).toEqual([ path.join(getPaths().api.functions, 'supertokensAuth2.ts'), path.join(getPaths().api.lib, 'supertokens2.ts'), path.join(getPaths().api.lib, 'supertokensAuth.ts'), ]) })
4,517
0
petrpan-code/redwoodjs/redwood/packages/cli-helpers/src/auth
petrpan-code/redwoodjs/redwood/packages/cli-helpers/src/auth/__tests__/authTasks.test.ts
// Have to use `var` here to avoid "Temporal Dead Zone" issues // eslint-disable-next-line var mockIsTypeScriptProject = true jest.mock('../../lib/project', () => ({ isTypeScriptProject: () => mockIsTypeScriptProject, })) jest.mock('../../lib', () => ({ transformTSToJS: (_path: string, data: string) => data, })) // mock Telemetry for CLI commands so they don't try to spawn a process jest.mock('@redwoodjs/telemetry', () => { return { errorTelemetry: () => jest.fn(), timedTelemetry: () => jest.fn(), } }) jest.mock('../../lib/paths', () => { const path = require('path') const actualPaths = jest.requireActual('../../lib/paths') const basedir = '/mock/setup/path' const app = mockIsTypeScriptProject ? 'App.tsx' : 'App.jsx' const routes = mockIsTypeScriptProject ? 'Routes.tsx' : 'Routes.jsx' return { resolveFile: actualPaths.resolveFile, getPaths: () => ({ api: { functions: '', src: '', lib: '', graphql: path.join(basedir, 'api/src/functions/graphql.ts'), }, web: { src: path.join(basedir, 'web/src'), app: path.join(basedir, `web/src/${app}`), routes: path.join(basedir, `web/src/${routes}`), }, base: path.join(basedir), }), } }) jest.mock('../../lib/project', () => { return { isTypeScriptProject: () => mockIsTypeScriptProject, getGraphqlPath: () => { const { getPaths } = require('../../lib/paths') return getPaths().api.graphql }, } }) // This will load packages/cli-helpers/__mocks__/fs.js jest.mock('fs') const mockFS = fs as unknown as Omit<jest.Mocked<typeof fs>, 'readdirSync'> & { __setMockFiles: (files: Record<string, string>) => void __getMockFiles: () => Record<string, string> readdirSync: () => string[] } import fs from 'fs' import path from 'path' import { getPaths } from '../../lib/paths' import type { AuthGeneratorCtx } from '../authTasks' import { addApiConfig, addConfigToWebApp, addConfigToRoutes, createWebAuth, hasAuthProvider, removeAuthProvider, } from '../authTasks' import { auth0WebAuthTsTemplate, clerkWebAuthTsTemplate, customApolloAppTsx, customPropsRoutesTsx, explicitReturnAppTsx, graphqlTs, legacyAuthWebAppTsx, nonStandardAuthDecoderGraphqlTs, routesTsx, useAuthRoutesTsx, webAppTsx, withAuthDecoderGraphqlTs, withoutRedwoodApolloAppTsx, } from './mockFsFiles' function platformPath(filePath: string) { return filePath.split('/').join(path.sep) } beforeEach(() => { mockIsTypeScriptProject = true jest.restoreAllMocks() mockFS.__setMockFiles({ [path.join( getPaths().base, platformPath('/templates/web/auth.ts.template') )]: '// web auth template', [getPaths().web.app]: webAppTsx, [getPaths().api.graphql]: graphqlTs, [getPaths().web.routes]: routesTsx, }) mockFS.readdirSync = () => { return ['auth.ts.template'] } }) describe('authTasks', () => { it('Should update App.{jsx,tsx}, Routes.{jsx,tsx} and add auth.ts (Auth0)', () => { const templatePath = path.join( getPaths().base, platformPath('/templates/web/auth.ts.template') ) mockFS.__setMockFiles({ ...mockFS.__getMockFiles(), [templatePath]: auth0WebAuthTsTemplate, }) const ctx: AuthGeneratorCtx = { provider: 'auth0', setupMode: 'FORCE', } addConfigToWebApp().task(ctx, {} as any) createWebAuth(getPaths().base, false).task(ctx) addConfigToRoutes().task() const authTsPath = path.join(getPaths().web.src, 'auth.ts') expect(fs.readFileSync(getPaths().web.app)).toMatchSnapshot() expect(fs.readFileSync(authTsPath)).toMatchSnapshot() expect(fs.readFileSync(getPaths().web.routes)).toMatchSnapshot() }) it('Should update App.{jsx,tsx}, Routes.{jsx,tsx} and add auth.ts (Clerk)', () => { const templatePath = path.join( getPaths().base, platformPath('/templates/web/auth.tsx.template') ) mockFS.__setMockFiles({ ...mockFS.__getMockFiles(), [templatePath]: clerkWebAuthTsTemplate, }) mockFS.readdirSync = () => { return ['auth.tsx.template'] } const ctx: AuthGeneratorCtx = { provider: 'clerk', setupMode: 'FORCE', } addConfigToWebApp().task(ctx, {} as any) createWebAuth(getPaths().base, false).task(ctx) addConfigToRoutes().task() const authTsPath = path.join(getPaths().web.src, 'auth.tsx') expect(fs.readFileSync(getPaths().web.app)).toMatchSnapshot() expect(fs.readFileSync(authTsPath)).toMatchSnapshot() expect(fs.readFileSync(getPaths().web.routes)).toMatchSnapshot() }) it('Should update App.tsx for legacy apps', () => { mockFS.__setMockFiles({ ...mockFS.__getMockFiles(), [getPaths().web.app]: legacyAuthWebAppTsx, }) const ctx: AuthGeneratorCtx = { provider: 'clerk', setupMode: 'FORCE', } addConfigToWebApp().task(ctx, {} as any) expect(fs.readFileSync(getPaths().web.app)).toMatchSnapshot() }) describe('Components with props', () => { it('Should add useAuth on the same line for single line components, and separate line for multiline components', () => { mockFS.__setMockFiles({ ...mockFS.__getMockFiles(), [getPaths().web.app]: customApolloAppTsx, [getPaths().web.routes]: customPropsRoutesTsx, }) const ctx: AuthGeneratorCtx = { provider: 'clerk', setupMode: 'FORCE', } addConfigToWebApp().task(ctx, {} as any) addConfigToRoutes().task() expect(fs.readFileSync(getPaths().web.app)).toMatchSnapshot() expect(fs.readFileSync(getPaths().web.routes)).toMatchSnapshot() }) it('Should not add useAuth if one already exists', () => { mockFS.__setMockFiles({ ...mockFS.__getMockFiles(), [getPaths().web.app]: customApolloAppTsx, [getPaths().web.routes]: useAuthRoutesTsx, }) const ctx: AuthGeneratorCtx = { provider: 'clerk', setupMode: 'FORCE', } addConfigToWebApp().task(ctx, {} as any) addConfigToRoutes().task() expect(fs.readFileSync(getPaths().web.app)).toMatchSnapshot() expect(fs.readFileSync(getPaths().web.routes)).toMatchSnapshot() }) }) describe('Customized App.js', () => { it('Should add auth config when using explicit return', () => { mockFS.__setMockFiles({ ...mockFS.__getMockFiles(), [getPaths().web.app]: explicitReturnAppTsx, }) const ctx: AuthGeneratorCtx = { provider: 'clerk', setupMode: 'FORCE', } addConfigToWebApp().task(ctx, {} as any) expect(fs.readFileSync(getPaths().web.app)).toMatchSnapshot() }) }) describe('Swapped out GraphQL client', () => { it('Should add auth config when app is missing RedwoodApolloProvider', () => { mockFS.__setMockFiles({ ...mockFS.__getMockFiles(), [getPaths().web.app]: withoutRedwoodApolloAppTsx, }) const ctx: AuthGeneratorCtx = { provider: 'clerk', setupMode: 'FORCE', } const task = { output: '' } as any addConfigToWebApp().task(ctx, task) expect(task.output).toMatch(/GraphQL.*useAuth/) expect(fs.readFileSync(getPaths().web.app)).toMatchSnapshot() }) }) describe('addApiConfig', () => { it('Adds authDecoder arg to default graphql.ts file', () => { addApiConfig({ replaceExistingImport: true, authDecoderImport: "import { authDecoder } from 'test-auth-api'", }) expect(fs.readFileSync(getPaths().api.graphql)).toMatchSnapshot() }) it("Doesn't add authDecoder arg if one already exists", () => { mockFS.__setMockFiles({ ...mockFS.__getMockFiles(), [getPaths().api.graphql]: withAuthDecoderGraphqlTs, }) addApiConfig({ replaceExistingImport: true, authDecoderImport: "import { authDecoder } from 'test-auth-api'", }) expect(fs.readFileSync(getPaths().api.graphql)).toMatchSnapshot() }) it("Doesn't add authDecoder arg if one already exists, even with a non-standard import name and arg placement", () => { mockFS.__setMockFiles({ ...mockFS.__getMockFiles(), [getPaths().api.graphql]: nonStandardAuthDecoderGraphqlTs, }) addApiConfig({ replaceExistingImport: true, authDecoderImport: "import { authDecoder } from 'test-auth-api'", }) expect(fs.readFileSync(getPaths().api.graphql)).toMatchSnapshot() }) }) describe('hasAuthProvider', () => { test('Single line', () => { expect(hasAuthProvider('<AuthProvider')).toBeTruthy() expect(hasAuthProvider('<AuthProvider>')).toBeTruthy() expect( hasAuthProvider( '<AuthProvider client={netlifyIdentity} type="netlify">' ) ).toBeTruthy() expect(hasAuthProvider('<AuthProviderFoo')).toBeFalsy() expect(hasAuthProvider('</AuthProvider>')).toBeFalsy() expect(hasAuthProvider('<FooAuthProvider')).toBeFalsy() expect(hasAuthProvider('<FooAuthProvider>')).toBeFalsy() }) test('Legacy auth single line', () => { const content = ` const App = () => ( <FatalErrorBoundary page={FatalErrorPage}> <RedwoodProvider titleTemplate="%PageTitle | %AppTitle"> <AuthProvider client={netlifyIdentity} type="netlify"> <RedwoodApolloProvider> <Routes /> </RedwoodApolloProvider> </AuthProvider> </RedwoodProvider> </FatalErrorBoundary> ) ` expect(hasAuthProvider(content)).toBeTruthy() }) test('Legacy auth multi-line', () => { const content = ` const App = () => ( <FatalErrorBoundary page={FatalErrorPage}> <RedwoodProvider titleTemplate="%PageTitle | %AppTitle"> <AuthProvider client={WebAuthnClient} type="dbAuth" config={{ fetchConfig: { credentials: 'include' } }} > <RedwoodApolloProvider graphQLClientConfig={{ httpLinkConfig: { credentials: 'include' }, }} > <Routes /> </RedwoodApolloProvider> </AuthProvider> </RedwoodProvider> </FatalErrorBoundary> ) ` expect(hasAuthProvider(content)).toBeTruthy() }) test('AuthProvider exists', () => { const content = ` const App = () => ( <FatalErrorBoundary page={FatalErrorPage}> <RedwoodProvider titleTemplate="%PageTitle | %AppTitle"> <AuthProvider> <RedwoodApolloProvider useAuth={useAuth}> <Routes /> </RedwoodApolloProvider> </AuthProvider> </RedwoodProvider> </FatalErrorBoundary> ) ` expect(hasAuthProvider(content)).toBeTruthy() }) test("AuthProvider doesn't exist", () => { const content = ` const App = () => ( <FatalErrorBoundary page={FatalErrorPage}> <RedwoodProvider titleTemplate="%PageTitle | %AppTitle"> <RedwoodApolloProvider> <Routes /> </RedwoodApolloProvider> </RedwoodProvider> </FatalErrorBoundary> ) ` expect(hasAuthProvider(content)).toBeFalsy() }) }) describe('removeAuthProvider', () => { test('Legacy auth single line', () => { const content = ` const App = () => ( <FatalErrorBoundary page={FatalErrorPage}> <RedwoodProvider titleTemplate="%PageTitle | %AppTitle"> <AuthProvider client={netlifyIdentity} type="netlify"> <RedwoodApolloProvider> <Routes /> </RedwoodApolloProvider> </AuthProvider> </RedwoodProvider> </FatalErrorBoundary> ) ` expect(removeAuthProvider(content)).toMatch(` const App = () => ( <FatalErrorBoundary page={FatalErrorPage}> <RedwoodProvider titleTemplate="%PageTitle | %AppTitle"> <RedwoodApolloProvider> <Routes /> </RedwoodApolloProvider> </RedwoodProvider> </FatalErrorBoundary> ) `) }) test('Legacy auth single line CRLF', () => { const content = ` const App = () => ( <FatalErrorBoundary page={FatalErrorPage}> <RedwoodProvider titleTemplate="%PageTitle | %AppTitle"> <AuthProvider client={netlifyIdentity} type="netlify"> <RedwoodApolloProvider> <Routes /> </RedwoodApolloProvider> </AuthProvider> </RedwoodProvider> </FatalErrorBoundary> ) `.replace(/\n/g, '\r\n') expect(removeAuthProvider(content)).toMatch( ` const App = () => ( <FatalErrorBoundary page={FatalErrorPage}> <RedwoodProvider titleTemplate="%PageTitle | %AppTitle"> <RedwoodApolloProvider> <Routes /> </RedwoodApolloProvider> </RedwoodProvider> </FatalErrorBoundary> ) `.replace(/\n/g, '\r\n') ) }) test('Legacy auth multi-line', () => { const content = ` const App = () => ( <FatalErrorBoundary page={FatalErrorPage}> <RedwoodProvider titleTemplate="%PageTitle | %AppTitle"> <AuthProvider client={WebAuthnClient} type="dbAuth" config={{ fetchConfig: { credentials: 'include' } }} > <RedwoodApolloProvider graphQLClientConfig={{ httpLinkConfig: { credentials: 'include' }, }} > <Routes /> </RedwoodApolloProvider> </AuthProvider> </RedwoodProvider> </FatalErrorBoundary> ) ` expect(removeAuthProvider(content)).toMatch(` const App = () => ( <FatalErrorBoundary page={FatalErrorPage}> <RedwoodProvider titleTemplate="%PageTitle | %AppTitle"> <RedwoodApolloProvider graphQLClientConfig={{ httpLinkConfig: { credentials: 'include' }, }} > <Routes /> </RedwoodApolloProvider> </RedwoodProvider> </FatalErrorBoundary> ) `) }) test('Legacy auth multi-line CRLF', () => { const content = ` const App = () => ( <FatalErrorBoundary page={FatalErrorPage}> <RedwoodProvider titleTemplate="%PageTitle | %AppTitle"> <AuthProvider client={WebAuthnClient} type="dbAuth" config={{ fetchConfig: { credentials: 'include' } }} > <RedwoodApolloProvider graphQLClientConfig={{ httpLinkConfig: { credentials: 'include' }, }} > <Routes /> </RedwoodApolloProvider> </AuthProvider> </RedwoodProvider> </FatalErrorBoundary> ) `.replace(/\n/g, '\r\n') expect(removeAuthProvider(content)).toMatch( ` const App = () => ( <FatalErrorBoundary page={FatalErrorPage}> <RedwoodProvider titleTemplate="%PageTitle | %AppTitle"> <RedwoodApolloProvider graphQLClientConfig={{ httpLinkConfig: { credentials: 'include' }, }} > <Routes /> </RedwoodApolloProvider> </RedwoodProvider> </FatalErrorBoundary> ) `.replace(/\n/g, '\r\n') ) }) test('AuthProvider exists', () => { const content = ` const App = () => ( <FatalErrorBoundary page={FatalErrorPage}> <RedwoodProvider titleTemplate="%PageTitle | %AppTitle"> <AuthProvider> <RedwoodApolloProvider useAuth={useAuth}> <Routes /> </RedwoodApolloProvider> </AuthProvider> </RedwoodProvider> </FatalErrorBoundary> ) ` expect(removeAuthProvider(content)).toMatch(` const App = () => ( <FatalErrorBoundary page={FatalErrorPage}> <RedwoodProvider titleTemplate="%PageTitle | %AppTitle"> <RedwoodApolloProvider useAuth={useAuth}> <Routes /> </RedwoodApolloProvider> </RedwoodProvider> </FatalErrorBoundary> ) `) }) test('AuthProvider exists CRLF', () => { const content = ` const App = () => ( <FatalErrorBoundary page={FatalErrorPage}> <RedwoodProvider titleTemplate="%PageTitle | %AppTitle"> <AuthProvider> <RedwoodApolloProvider useAuth={useAuth}> <Routes /> </RedwoodApolloProvider> </AuthProvider> </RedwoodProvider> </FatalErrorBoundary> ) `.replace(/\n/g, '\r\n') expect(removeAuthProvider(content)).toMatch( ` const App = () => ( <FatalErrorBoundary page={FatalErrorPage}> <RedwoodProvider titleTemplate="%PageTitle | %AppTitle"> <RedwoodApolloProvider useAuth={useAuth}> <Routes /> </RedwoodApolloProvider> </RedwoodProvider> </FatalErrorBoundary> ) `.replace(/\n/g, '\r\n') ) }) test("AuthProvider doesn't exist", () => { const content = ` const App = () => ( <FatalErrorBoundary page={FatalErrorPage}> <RedwoodProvider titleTemplate="%PageTitle | %AppTitle"> <RedwoodApolloProvider> <Routes /> </RedwoodApolloProvider> </RedwoodProvider> </FatalErrorBoundary> ) ` expect(removeAuthProvider(content)).toMatch(` const App = () => ( <FatalErrorBoundary page={FatalErrorPage}> <RedwoodProvider titleTemplate="%PageTitle | %AppTitle"> <RedwoodApolloProvider> <Routes /> </RedwoodApolloProvider> </RedwoodProvider> </FatalErrorBoundary> ) `) }) }) it('writes an auth.ts file for TS projects', () => { const ctx: AuthGeneratorCtx = { provider: 'auth0', setupMode: 'FORCE', } createWebAuth(getPaths().base, false).task(ctx) expect( fs.readFileSync(path.join(getPaths().web.src, 'auth.ts')) ).toMatchSnapshot() }) it('writes an auth.js file for JS projects', () => { mockIsTypeScriptProject = false mockFS.__setMockFiles({ ...mockFS.__getMockFiles(), [getPaths().web.app]: webAppTsx, }) const ctx: AuthGeneratorCtx = { provider: 'auth0', setupMode: 'FORCE', } createWebAuth(getPaths().base, false).task(ctx) expect( fs.readFileSync(path.join(getPaths().web.src, 'auth.js')) ).toMatchSnapshot() }) })
4,519
0
petrpan-code/redwoodjs/redwood/packages/cli-helpers/src/auth
petrpan-code/redwoodjs/redwood/packages/cli-helpers/src/auth/__tests__/setupHelpers.test.ts
globalThis.__dirname = __dirname // mock Telemetry for CLI commands so they don't try to spawn a process jest.mock('@redwoodjs/telemetry', () => { return { errorTelemetry: () => jest.fn(), timedTelemetry: () => jest.fn(), } }) jest.mock('../../lib/paths', () => { const path = require('path') const __dirname = path.resolve() return { getPaths: () => ({ api: { src: path.join(__dirname, '../create-redwood-app/template/api/src'), functions: path.join( __dirname, '../create-redwood-app/template/api/src/functions' ), lib: path.join(__dirname, '../create-redwood-app/template/api/src/lib'), }, web: { src: '' }, base: path.join(__dirname, '../create-redwood-app/template'), }), } }) jest.mock('../../lib/project', () => ({ isTypeScriptProject: () => true, })) jest.mock('execa', () => {}) jest.mock('listr2') jest.mock('prompts', () => jest.fn(() => ({ answer: true }))) import fs from 'fs' import path from 'path' import { Listr } from 'listr2' import prompts from 'prompts' // import * as auth from '../auth' import { standardAuthHandler } from '../setupHelpers' describe('Auth generator tests', () => { const processExitSpy = jest .spyOn<NodeJS.Process, any>(process, 'exit') .mockImplementation((_code: any) => {}) const mockListrRun = jest.fn() ;(Listr as jest.MockedFunction<jest.Mock>).mockImplementation(() => { return { run: mockListrRun, } }) const fsSpy = jest.spyOn(fs, 'writeFileSync').mockImplementation(() => {}) afterEach(() => { processExitSpy.mockReset() fsSpy.mockReset() ;(prompts as unknown as jest.Mock).mockClear() mockListrRun.mockClear() }) it('Successfully executes the handler for Supertokens', async () => { await standardAuthHandler({ basedir: path.join(__dirname, 'fixtures/supertokensSetup'), provider: 'supertokens', webAuthn: false, forceArg: false, }) expect(mockListrRun).toHaveBeenCalledTimes(1) expect(processExitSpy).not.toHaveBeenCalledWith(1) // TODO: Add something like this back in when we've added support for // prompting the user // expect(prompts).toHaveBeenCalledTimes(1) // expect(prompts).toHaveBeenCalledWith( // expect.objectContaining({ // message: expect.stringMatching( // /Overwrite existing [/\\]api[/\\]src[/\\]lib[/\\]auth.ts\?/ // ), // }) // ) }) it('Successfully executes the handler for Netlify without prompting the user when --force is true', async () => { await standardAuthHandler({ basedir: path.join(__dirname, 'fixtures/supertokensSetup'), provider: 'supertokens', webAuthn: false, forceArg: true, }) expect(mockListrRun).toHaveBeenCalledTimes(1) expect(processExitSpy).not.toHaveBeenCalledWith(1) expect(prompts).toHaveBeenCalledTimes(0) }) it('Successfully executes the handler for dbAuth', async () => { await standardAuthHandler({ basedir: path.join(__dirname, 'fixtures/dbAuthSetup'), provider: 'dbAuth', webAuthn: false, forceArg: false, }) expect(mockListrRun).toHaveBeenCalledTimes(1) expect(processExitSpy).not.toHaveBeenCalledWith(1) // TODO: Add this back in later // expect(prompts).toHaveBeenCalledTimes(1) // expect(prompts).toHaveBeenCalledWith( // expect.objectContaining({ // message: expect.stringMatching( // /Overwrite existing [/\\]api[/\\]src[/\\]lib[/\\]auth.ts\?/ // ), // }) // ) }) })
4,520
0
petrpan-code/redwoodjs/redwood/packages/cli-helpers/src/auth/__tests__
petrpan-code/redwoodjs/redwood/packages/cli-helpers/src/auth/__tests__/__snapshots__/authTasks.test.ts.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`authTasks Components with props Should add useAuth on the same line for single line components, and separate line for multiline components 1`] = ` "import { FatalErrorBoundary, RedwoodProvider } from '@redwoodjs/web' import { RedwoodApolloProvider } from '@redwoodjs/web/apollo' import FatalErrorPage from 'src/pages/FatalErrorPage' import Routes from 'src/Routes' import { AuthProvider, useAuth } from './auth' import './index.css' const App = () => ( <FatalErrorBoundary page={FatalErrorPage}> <RedwoodProvider titleTemplate="%PageTitle | %AppTitle"> <AuthProvider> <RedwoodApolloProvider useAuth={useAuth} graphQLClientConfig={{ cache }}> <Routes /> </RedwoodApolloProvider> </AuthProvider> </RedwoodProvider> </FatalErrorBoundary> ) export default App " `; exports[`authTasks Components with props Should add useAuth on the same line for single line components, and separate line for multiline components 2`] = ` "// In this file, all Page components from 'src/pages\` are auto-imported. Nested // directories are supported, and should be uppercase. Each subdirectory will be // prepended onto the component name. // // Examples: // // 'src/pages/HomePage/HomePage.js' -> HomePage // 'src/pages/Admin/BooksPage/BooksPage.js' -> AdminBooksPage import { Router, Route } from '@redwoodjs/router' import { useAuth } from './auth' const Routes = () => { return ( <Router useAuth={useAuth} pageLoadingDelay={400} trailingSlashes="always" paramTypes={{ foo: { match: /foo/, parse: (value: string) => value.split('').reverse().join(''), }, }} > <Route notfound page={NotFoundPage} /> </Router> ) } export default Routes " `; exports[`authTasks Components with props Should not add useAuth if one already exists 1`] = ` "import { FatalErrorBoundary, RedwoodProvider } from '@redwoodjs/web' import { RedwoodApolloProvider } from '@redwoodjs/web/apollo' import FatalErrorPage from 'src/pages/FatalErrorPage' import Routes from 'src/Routes' import { AuthProvider, useAuth } from './auth' import './index.css' const App = () => ( <FatalErrorBoundary page={FatalErrorPage}> <RedwoodProvider titleTemplate="%PageTitle | %AppTitle"> <AuthProvider> <RedwoodApolloProvider useAuth={useAuth} graphQLClientConfig={{ cache }}> <Routes /> </RedwoodApolloProvider> </AuthProvider> </RedwoodProvider> </FatalErrorBoundary> ) export default App " `; exports[`authTasks Components with props Should not add useAuth if one already exists 2`] = ` "// In this file, all Page components from 'src/pages\` are auto-imported. Nested // directories are supported, and should be uppercase. Each subdirectory will be // prepended onto the component name. // // Examples: // // 'src/pages/HomePage/HomePage.js' -> HomePage // 'src/pages/Admin/BooksPage/BooksPage.js' -> AdminBooksPage import { Router, Route } from '@redwoodjs/router' import { useAuth } from './auth' const Routes = () => { return ( <Router pageLoadingDelay={400} trailingSlashes="always" paramTypes={{ foo: { match: /foo/, parse: (value: string) => value.split('').reverse().join(''), }, }} useAuth={() => ({ loading: false, isAuthenticated: false })} > <Route notfound page={NotFoundPage} /> </Router> ) } export default Routes " `; exports[`authTasks Customized App.js Should add auth config when using explicit return 1`] = ` "import { useEffect } from 'react' import { FatalErrorBoundary, RedwoodProvider } from '@redwoodjs/web' import { RedwoodApolloProvider } from '@redwoodjs/web/apollo' import FatalErrorPage from 'src/pages/FatalErrorPage' import Routes from 'src/Routes' import { AuthProvider, useAuth } from './auth' import './index.css' const App = (props) => { const { cache } = props useEffect(() => { console.log('Running my custom useEffect hook on each render.') }) return ( <FatalErrorBoundary page={FatalErrorPage}> <RedwoodProvider titleTemplate="%PageTitle | %AppTitle"> <AuthProvider> <RedwoodApolloProvider useAuth={useAuth}> <AnotherProvider> <Routes /> </AnotherProvider> </RedwoodApolloProvider> </AuthProvider> </RedwoodProvider> </FatalErrorBoundary> ) } export default App " `; exports[`authTasks Should update App.{jsx,tsx}, Routes.{jsx,tsx} and add auth.ts (Auth0) 1`] = ` "import { FatalErrorBoundary, RedwoodProvider } from '@redwoodjs/web' import { RedwoodApolloProvider } from '@redwoodjs/web/apollo' import FatalErrorPage from 'src/pages/FatalErrorPage' import Routes from 'src/Routes' import { AuthProvider, useAuth } from './auth' import './index.css' const App = () => ( <FatalErrorBoundary page={FatalErrorPage}> <RedwoodProvider titleTemplate="%PageTitle | %AppTitle"> <AuthProvider> <RedwoodApolloProvider useAuth={useAuth}> <Routes /> </RedwoodApolloProvider> </AuthProvider> </RedwoodProvider> </FatalErrorBoundary> ) export default App " `; exports[`authTasks Should update App.{jsx,tsx}, Routes.{jsx,tsx} and add auth.ts (Auth0) 2`] = ` "import { Auth0Client } from '@auth0/auth0-spa-js' import { createAuth } from '@redwoodjs/auth-auth0-web' const auth0 = new Auth0Client({ domain: process.env.AUTH0_DOMAIN || '', client_id: process.env.AUTH0_CLIENT_ID || '', redirect_uri: process.env.AUTH0_REDIRECT_URI, // ** NOTE ** Storing tokens in browser local storage provides persistence across page refreshes and browser tabs. // However, if an attacker can achieve running JavaScript in the SPA using a cross-site scripting (XSS) attack, // they can retrieve the tokens stored in local storage. // https://auth0.com/docs/libraries/auth0-spa-js#change-storage-options cacheLocation: 'localstorage', audience: process.env.AUTH0_AUDIENCE, // @MARK useRefreshTokens is required for automatically extending sessions // beyond that set in the initial JWT expiration. // // @see https://auth0.com/docs/tokens/refresh-tokens // useRefreshTokens: true, }) export const { AuthProvider, useAuth } = createAuth(auth0) " `; exports[`authTasks Should update App.{jsx,tsx}, Routes.{jsx,tsx} and add auth.ts (Auth0) 3`] = ` "// In this file, all Page components from 'src/pages\` are auto-imported. Nested // directories are supported, and should be uppercase. Each subdirectory will be // prepended onto the component name. // // Examples: // // 'src/pages/HomePage/HomePage.js' -> HomePage // 'src/pages/Admin/BooksPage/BooksPage.js' -> AdminBooksPage import { Router, Route } from '@redwoodjs/router' import { useAuth } from './auth' const Routes = () => { return ( <Router useAuth={useAuth}> <Route notfound page={NotFoundPage} /> </Router> ) } export default Routes " `; exports[`authTasks Should update App.{jsx,tsx}, Routes.{jsx,tsx} and add auth.ts (Clerk) 1`] = ` "import { FatalErrorBoundary, RedwoodProvider } from '@redwoodjs/web' import { RedwoodApolloProvider } from '@redwoodjs/web/apollo' import FatalErrorPage from 'src/pages/FatalErrorPage' import Routes from 'src/Routes' import { AuthProvider, useAuth } from './auth' import './index.css' const App = () => ( <FatalErrorBoundary page={FatalErrorPage}> <RedwoodProvider titleTemplate="%PageTitle | %AppTitle"> <AuthProvider> <RedwoodApolloProvider useAuth={useAuth}> <Routes /> </RedwoodApolloProvider> </AuthProvider> </RedwoodProvider> </FatalErrorBoundary> ) export default App " `; exports[`authTasks Should update App.{jsx,tsx}, Routes.{jsx,tsx} and add auth.ts (Clerk) 2`] = ` "import React, { useEffect } from 'react' import { ClerkLoaded, ClerkProvider, useUser } from '@clerk/clerk-react' import { createAuth } from '@redwoodjs/auth-clerk-web' // You can set user roles in a "roles" array on the public metadata in Clerk. // // Also, you need to add three env variables: CLERK_FRONTEND_API_URL for web and // CLERK_API_KEY plus CLERK_JWT_KEY for api. All three can be found under "API Keys" // on your Clerk.dev dashboard. // // Lastly, be sure to add the key "CLERK_FRONTEND_API_URL" in your app's redwood.toml // [web] config "includeEnvironmentVariables" setting. export const { AuthProvider: ClerkRwAuthProvider, useAuth } = createAuth() interface Props { children: React.ReactNode } const ClerkStatusUpdater = () => { const { isSignedIn, user, isLoaded } = useUser() const { reauthenticate } = useAuth() useEffect(() => { if (isLoaded) { reauthenticate() } }, [isSignedIn, user, reauthenticate, isLoaded]) return null } export const AuthProvider = ({ children }: Props) => { const frontendApi = process.env.CLERK_FRONTEND_API_URL if (!frontendApi) { throw new Error('Need to define env variable CLERK_FRONTEND_API_URL') } return ( <ClerkProvider frontendApi={frontendApi} navigate={(to) => navigate(to)}> <ClerkRwAuthProvider> <ClerkLoaded>{children}</ClerkLoaded> <ClerkStatusUpdater /> </ClerkRwAuthProvider> </ClerkProvider> ) } " `; exports[`authTasks Should update App.{jsx,tsx}, Routes.{jsx,tsx} and add auth.ts (Clerk) 3`] = ` "// In this file, all Page components from 'src/pages\` are auto-imported. Nested // directories are supported, and should be uppercase. Each subdirectory will be // prepended onto the component name. // // Examples: // // 'src/pages/HomePage/HomePage.js' -> HomePage // 'src/pages/Admin/BooksPage/BooksPage.js' -> AdminBooksPage import { Router, Route } from '@redwoodjs/router' import { useAuth } from './auth' const Routes = () => { return ( <Router useAuth={useAuth}> <Route notfound page={NotFoundPage} /> </Router> ) } export default Routes " `; exports[`authTasks Should update App.tsx for legacy apps 1`] = ` "import netlifyIdentity from 'netlify-identity-widget' import { isBrowser } from '@redwoodjs/prerender/browserUtils' import { FatalErrorBoundary, RedwoodProvider } from '@redwoodjs/web' import { RedwoodApolloProvider } from '@redwoodjs/web/apollo' import FatalErrorPage from 'src/pages/FatalErrorPage' import Routes from 'src/Routes' import { AuthProvider, useAuth } from './auth' import './index.css' isBrowser && netlifyIdentity.init() const App = () => ( <FatalErrorBoundary page={FatalErrorPage}> <RedwoodProvider titleTemplate="%PageTitle | %AppTitle"> <AuthProvider> <RedwoodApolloProvider useAuth={useAuth}> <Routes /> </RedwoodApolloProvider> </AuthProvider> </RedwoodProvider> </FatalErrorBoundary> ) export default App " `; exports[`authTasks Swapped out GraphQL client Should add auth config when app is missing RedwoodApolloProvider 1`] = ` "import { FatalErrorBoundary, RedwoodProvider } from '@redwoodjs/web' import FatalErrorPage from 'src/pages/FatalErrorPage' import Routes from 'src/Routes' import { AuthProvider, useAuth } from './auth' import './index.css' const queryClient = {} const App = () => ( <FatalErrorBoundary page={FatalErrorPage}> <RedwoodProvider titleTemplate="%PageTitle | %AppTitle"> <AuthProvider> <QueryClientProvider client={queryClient}> <RedwoodReactQueryProvider> <Routes /> </RedwoodReactQueryProvider> </QueryClientProvider> </AuthProvider> </RedwoodProvider> </FatalErrorBoundary> ) export default App " `; exports[`authTasks addApiConfig Adds authDecoder arg to default graphql.ts file 1`] = ` "import { authDecoder } from 'test-auth-api' import { createGraphQLHandler } from '@redwoodjs/graphql-server' import directives from 'src/directives/**/*.{js,ts}' import sdls from 'src/graphql/**/*.sdl.{js,ts}' import services from 'src/services/**/*.{js,ts}' import { getCurrentUser } from 'src/lib/auth' import { db } from 'src/lib/db' import { logger } from 'src/lib/logger' export const handler = createGraphQLHandler({ authDecoder, getCurrentUser, loggerConfig: { logger, options: {} }, directives, sdls, services, onException: () => { // Disconnect from your database with an unhandled exception. db.$disconnect() }, }) " `; exports[`authTasks addApiConfig Doesn't add authDecoder arg if one already exists 1`] = ` "import { authDecoder } from 'test-auth-api' import { createGraphQLHandler } from '@redwoodjs/graphql-server' import directives from 'src/directives/**/*.{js,ts}' import sdls from 'src/graphql/**/*.sdl.{js,ts}' import services from 'src/services/**/*.{js,ts}' import { getCurrentUser } from 'src/lib/auth' import { db } from 'src/lib/db' import { logger } from 'src/lib/logger' export const handler = createGraphQLHandler({ authDecoder, getCurrentUser, loggerConfig: { logger, options: {} }, directives, sdls, services, onException: () => { // Disconnect from your database with an unhandled exception. db.$disconnect() }, }) " `; exports[`authTasks addApiConfig Doesn't add authDecoder arg if one already exists, even with a non-standard import name and arg placement 1`] = ` "import { authDecoder } from 'test-auth-api' import { createGraphQLHandler } from '@redwoodjs/graphql-server' import directives from 'src/directives/**/*.{js,ts}' import sdls from 'src/graphql/**/*.sdl.{js,ts}' import services from 'src/services/**/*.{js,ts}' import { getCurrentUser } from 'src/lib/auth' import { db } from 'src/lib/db' import { logger } from 'src/lib/logger' export const handler = createGraphQLHandler({ getCurrentUser, loggerConfig: { logger, options: {} }, directives, sdls, services, onException: () => { // Disconnect from your database with an unhandled exception. db.$disconnect() }, authDecoder, }) " `; exports[`authTasks writes an auth.js file for JS projects 1`] = `"// web auth template"`; exports[`authTasks writes an auth.ts file for TS projects 1`] = `"// web auth template"`;
4,540
0
petrpan-code/redwoodjs/redwood/packages/cli-helpers/src/lib
petrpan-code/redwoodjs/redwood/packages/cli-helpers/src/lib/__tests__/index.test.ts
import { prettify } from '../index' jest.mock('../paths', () => { return { getPaths: () => { return { base: '../../../../__fixtures__/example-todo-main', } }, } }) test('prettify formats tsx content', () => { const content = `import React from 'react' interface Props { foo: number, bar: number } const FooBarComponent: React.FC<Props> = ({ foo, bar }) => { if (foo % 3 === 0 && bar % 5 === 0) { return <>FooBar</> } if (foo % 3 === 0 || bar % 3 === 0) { return <>Foo</>; } if (foo % 5 === 0 || bar % 5 === 0) { return <>Bar</>} return <>{foo}, {bar}</>}` expect(prettify('FooBarComponent.template.tsx', content)).toMatchSnapshot() })
4,541
0
petrpan-code/redwoodjs/redwood/packages/cli-helpers/src/lib
petrpan-code/redwoodjs/redwood/packages/cli-helpers/src/lib/__tests__/project.test.ts
import fs from 'fs' import toml from '@iarna/toml' import { updateTomlConfig, addEnvVar } from '../project' // Replace with the correct path to your module jest.mock('fs') const defaultRedwoodToml = { web: { title: 'Redwood App', port: 8910, apiUrl: '/.redwood/functions', includeEnvironmentVariables: [], }, api: { port: 8911, }, } const getRedwoodToml = () => { return defaultRedwoodToml } jest.mock('@redwoodjs/project-config', () => { return { getPaths: () => { return { generated: { base: '.redwood', }, base: '', } }, getConfigPath: () => { return '.redwood.toml' }, getConfig: () => { return getRedwoodToml() }, } }) describe('addEnvVar', () => { let envFileContent = '' describe('addEnvVar adds environment variables as part of a setup task', () => { beforeEach(() => { jest.spyOn(fs, 'existsSync').mockImplementation(() => { return true }) jest.spyOn(fs, 'readFileSync').mockImplementation(() => { return envFileContent }) jest.spyOn(fs, 'writeFileSync').mockImplementation((envPath, envFile) => { expect(envPath).toContain('.env') return envFile }) }) afterEach(() => { jest.restoreAllMocks() envFileContent = '' }) it('should add a new environment variable when it does not exist', () => { envFileContent = 'EXISTING_VAR = value\n# CommentedVar = 123\n' const file = addEnvVar('NEW_VAR', 'new_value', 'New Variable Comment') expect(file).toMatchSnapshot() }) it('should add a new environment variable when it does not exist when existing envars have no spacing', () => { envFileContent = 'EXISTING_VAR=value\n# CommentedVar = 123\n' const file = addEnvVar('NEW_VAR', 'new_value', 'New Variable Comment') expect(file).toMatchSnapshot() }) it('should add a comment that the existing environment variable value was not changed, but include its new value as a comment', () => { envFileContent = 'EXISTING_VAR=value\n# CommentedVar=123\n' const file = addEnvVar( 'EXISTING_VAR', 'new_value', 'Updated existing variable Comment' ) expect(file).toMatchSnapshot() }) it('should handle existing environment variables with quoted values', () => { envFileContent = `EXISTING_VAR = "value"\n# CommentedVar = 123\n` const file = addEnvVar('EXISTING_VAR', 'value', 'New Variable Comment') expect(file).toMatchSnapshot() }) it('should handle existing environment variables with quoted values and no spacing', () => { envFileContent = `EXISTING_VAR="value"\n# CommentedVar=123\n` const file = addEnvVar('EXISTING_VAR', 'value', 'New Variable Comment') expect(file).toMatchSnapshot() }) it('should handle existing environment variables and new value with quoted values by not updating the original value', () => { envFileContent = `EXISTING_VAR = "value"\n# CommentedVar = 123\n` const file = addEnvVar( 'EXISTING_VAR', 'new_value', 'New Variable Comment' ) expect(file).toMatchSnapshot() }) }) }) describe('updateTomlConfig', () => { describe('updateTomlConfig configures a new CLI plugin', () => { beforeEach(() => { jest.spyOn(fs, 'existsSync').mockImplementation(() => { return true }) jest.spyOn(fs, 'readFileSync').mockImplementation(() => { return toml.stringify(defaultRedwoodToml) }) jest .spyOn(fs, 'writeFileSync') .mockImplementation((tomlPath, tomlFile) => { expect(tomlPath).toContain('redwood.toml') return tomlFile }) }) afterEach(() => { jest.restoreAllMocks() }) it('adds when experimental cli is not configured', () => { const file = updateTomlConfig( '@example/test-package-when-cli-not-configured' ) expect(file).toMatchSnapshot() }) it('adds when experimental cli has some plugins configured', () => { defaultRedwoodToml['experimental'] = { cli: { autoInstall: true, plugins: [ { package: '@existing-example/some-package-when-cli-has-some-packages-configured', }, ], }, } const file = updateTomlConfig('@example/test-package-name') expect(file).toMatchSnapshot() }) it('adds when experimental cli is setup but has no plugins configured', () => { defaultRedwoodToml['experimental'] = { cli: { autoInstall: true, }, } const file = updateTomlConfig( '@example/test-package-when-no-plugins-configured' ) expect(file).toMatchSnapshot() }) it('adds package but keeps autoInstall false', () => { defaultRedwoodToml['experimental'] = { cli: { autoInstall: false, }, } const file = updateTomlConfig( '@example/test-package-when-autoInstall-false' ) expect(file).toMatchSnapshot() }) it('does not add duplicate place when experimental cli has that plugin configured', () => { defaultRedwoodToml['experimental'] = { cli: { autoInstall: true, plugins: [ { package: '@existing-example/some-package-name-already-exists', }, ], }, } const file = updateTomlConfig( '@existing-example/some-package-name-already-exists' ) expect(file).toMatchSnapshot() }) }) })
4,542
0
petrpan-code/redwoodjs/redwood/packages/cli-helpers/src/lib
petrpan-code/redwoodjs/redwood/packages/cli-helpers/src/lib/__tests__/version.test.ts
jest.mock('@redwoodjs/project-config', () => { return { getPaths: () => { return { base: '', } }, } }) jest.mock('fs') import fs from 'fs' import { getCompatibilityData } from '../version' const EXAMPLE_PACKUMENT = { _id: '@scope/package-name', _rev: 'a1b2c3a1b2c3a1b2c3a1b2c3a1b2c3a1b2c3', name: '@scope/package-name', 'dist-tags': { latest: '0.0.3', }, versions: { '0.0.1': { name: '@scope/package-name', version: '0.0.1', main: 'index.js', scripts: { test: 'echo "Error: no test specified" && exit 1', }, author: '', license: 'ISC', description: '', dependencies: { 'some-package': '1.2.3', }, _id: '@scope/[email protected]', _nodeVersion: '18.16.0', _npmVersion: '9.5.1', dist: { integrity: 'sha512-somehashvalue', shasum: 'somehashvalue', tarball: 'someurl', fileCount: 8, unpackedSize: 1024, signatures: [ { keyid: 'SHA256:somehashvalue', sig: 'somehashvalue', }, ], }, _npmUser: { name: 'someuser', email: 'someemail', }, directories: {}, maintainers: [ { name: 'someuser', email: 'someemail', }, ], _npmOperationalInternal: { host: 'somes3', tmp: 'sometmp', }, _hasShrinkwrap: false, }, '0.0.2': { name: '@scope/package-name', version: '0.0.2', main: 'index.js', scripts: { test: 'echo "Error: no test specified" && exit 1', }, author: '', license: 'ISC', description: '', dependencies: { 'some-package': '1.2.3', }, engines: { redwoodjs: '^5.1.0', }, _id: '@scope/[email protected]', _nodeVersion: '20.2.0', _npmVersion: '9.6.6', dist: { integrity: 'sha512-somehashvalue', shasum: 'somehashvalue', tarball: 'someurl', fileCount: 8, unpackedSize: 1024, signatures: [ { keyid: 'SHA256:somehashvalue', sig: 'somehashvalue', }, ], }, _npmUser: { name: 'someuser', email: 'someemail', }, directories: {}, maintainers: [ { name: 'someuser', email: 'someemail', }, ], _npmOperationalInternal: { host: 'somes3', tmp: 'sometmp', }, _hasShrinkwrap: false, }, '0.0.3': { name: '@scope/package-name', version: '0.0.3', main: 'index.js', scripts: { test: 'echo "Error: no test specified" && exit 1', }, author: '', license: 'ISC', description: '', dependencies: { 'some-package': '1.2.3', }, engines: { redwoodjs: '^6.0.0', }, _id: '@scope/[email protected]', _nodeVersion: '20.2.0', _npmVersion: '9.6.6', dist: { integrity: 'sha512-somehashvalue', shasum: 'somehashvalue', tarball: 'someurl', fileCount: 8, unpackedSize: 1024, signatures: [ { keyid: 'SHA256:somehashvalue', sig: 'somehashvalue', }, ], }, _npmUser: { name: 'someuser', email: 'someemail', }, directories: {}, maintainers: [ { name: 'someuser', email: 'someemail', }, ], _npmOperationalInternal: { host: 'somes3', tmp: 'sometmp', }, _hasShrinkwrap: false, }, }, time: { created: '2023-05-10T12:10:52.090Z', '0.0.1': '2023-05-10T12:10:52.344Z', '0.0.2': '2023-07-15T19:45:25.905Z', }, maintainers: [ { name: 'someuser', email: 'someemail', }, ], license: 'ISC', readme: 'ERROR: No README data found!', readmeFilename: '', author: { name: 'someuser', }, } describe('version compatibility detection', () => { beforeEach(() => { jest.spyOn(global, 'fetch').mockImplementation(() => { return { json: () => { return EXAMPLE_PACKUMENT }, } as any }) jest.spyOn(fs, 'readFileSync').mockImplementation(() => { return JSON.stringify({ devDependencies: { '@redwoodjs/core': '^6.0.0', }, }) }) }) test('throws for some fetch related error', async () => { // Mock the fetch function to throw an error jest.spyOn(global, 'fetch').mockImplementation(() => { throw new Error('Some fetch related error') }) await expect( getCompatibilityData('some-package', 'latest') ).rejects.toThrowErrorMatchingInlineSnapshot(`"Some fetch related error"`) // Mock the json parsing to throw an error jest.spyOn(global, 'fetch').mockImplementation(() => { return { json: () => { throw new Error('Some json parsing error') }, } as any }) await expect( getCompatibilityData('some-package', 'latest') ).rejects.toThrowErrorMatchingInlineSnapshot(`"Some json parsing error"`) }) test('throws for some packument related error', async () => { jest.spyOn(global, 'fetch').mockImplementation(() => { return { json: () => { return { error: 'Some packument related error', } }, } as any }) await expect( getCompatibilityData('some-package', 'latest') ).rejects.toThrowErrorMatchingInlineSnapshot( `"Some packument related error"` ) }) test('throws if preferred version is not found', async () => { await expect( getCompatibilityData('@scope/package-name', '0.0.4') ).rejects.toThrowErrorMatchingInlineSnapshot( `"The package '@scope/package-name' does not have a version '0.0.4'"` ) }) test('throws if preferred tag is not found', async () => { await expect( getCompatibilityData('@scope/package-name', 'next') ).rejects.toThrowErrorMatchingInlineSnapshot( `"The package '@scope/package-name' does not have a tag 'next'"` ) }) test('throws if no latest version could be found', async () => { jest.spyOn(global, 'fetch').mockImplementation(() => { return { json: () => { return { ...EXAMPLE_PACKUMENT, 'dist-tags': {}, } }, } as any }) await expect( getCompatibilityData('@scope/package-name', 'latest') ).rejects.toThrowErrorMatchingInlineSnapshot( `"The package '@scope/package-name' does not have a tag 'latest'"` ) }) test('returns the preferred version if it is compatible', async () => { expect(await getCompatibilityData('@scope/package-name', '0.0.3')).toEqual({ preferred: { tag: 'latest', version: '0.0.3', }, compatible: { tag: 'latest', version: '0.0.3', }, }) }) test('returns the latest compatible version if the preferred version is not compatible', async () => { expect(await getCompatibilityData('@scope/package-name', '0.0.2')).toEqual({ preferred: { tag: undefined, version: '0.0.2', }, compatible: { tag: 'latest', version: '0.0.3', }, }) }) test('returns the latest compatible version when given a tag', async () => { expect(await getCompatibilityData('@scope/package-name', 'latest')).toEqual( { preferred: { tag: 'latest', version: '0.0.3', }, compatible: { tag: 'latest', version: '0.0.3', }, } ) jest.spyOn(fs, 'readFileSync').mockImplementation(() => { return JSON.stringify({ devDependencies: { '@redwoodjs/core': '5.2.0', }, }) }) expect(await getCompatibilityData('@scope/package-name', 'latest')).toEqual( { preferred: { tag: 'latest', version: '0.0.3', }, compatible: { tag: undefined, version: '0.0.2', }, } ) }) test('throws if no compatible version could be found', async () => { jest.spyOn(fs, 'readFileSync').mockImplementation(() => { return JSON.stringify({ devDependencies: { '@redwoodjs/core': '7.0.0', }, }) }) expect( getCompatibilityData('@scope/package-name', 'latest') ).rejects.toThrowErrorMatchingInlineSnapshot( `"No compatible version of '@scope/package-name' was found"` ) }) })
4,543
0
petrpan-code/redwoodjs/redwood/packages/cli-helpers/src/lib/__tests__
petrpan-code/redwoodjs/redwood/packages/cli-helpers/src/lib/__tests__/__snapshots__/index.test.ts.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`prettify formats tsx content 1`] = ` "import React from 'react' interface Props { foo: number bar: number } const FooBarComponent: React.FC<Props> = ({ foo, bar }) => { if (foo % 3 === 0 && bar % 5 === 0) { return <>FooBar</> } if (foo % 3 === 0 || bar % 3 === 0) { return <>Foo</> } if (foo % 5 === 0 || bar % 5 === 0) { return <>Bar</> } return ( <> {foo}, {bar} </> ) } " `;
4,544
0
petrpan-code/redwoodjs/redwood/packages/cli-helpers/src/lib/__tests__
petrpan-code/redwoodjs/redwood/packages/cli-helpers/src/lib/__tests__/__snapshots__/project.test.ts.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`addEnvVar addEnvVar adds environment variables as part of a setup task should add a comment that the existing environment variable value was not changed, but include its new value as a comment 1`] = ` "EXISTING_VAR=value # CommentedVar=123 # Note: The existing environment variable EXISTING_VAR was not overwritten. Uncomment to use its new value. # Updated existing variable Comment # EXISTING_VAR = new_value " `; exports[`addEnvVar addEnvVar adds environment variables as part of a setup task should add a new environment variable when it does not exist 1`] = ` "EXISTING_VAR = value # CommentedVar = 123 # New Variable Comment NEW_VAR = new_value " `; exports[`addEnvVar addEnvVar adds environment variables as part of a setup task should add a new environment variable when it does not exist when existing envars have no spacing 1`] = ` "EXISTING_VAR=value # CommentedVar = 123 # New Variable Comment NEW_VAR = new_value " `; exports[`addEnvVar addEnvVar adds environment variables as part of a setup task should handle existing environment variables and new value with quoted values by not updating the original value 1`] = ` "EXISTING_VAR = "value" # CommentedVar = 123 # Note: The existing environment variable EXISTING_VAR was not overwritten. Uncomment to use its new value. # New Variable Comment # EXISTING_VAR = new_value " `; exports[`addEnvVar addEnvVar adds environment variables as part of a setup task should handle existing environment variables with quoted values 1`] = ` "EXISTING_VAR = "value" # CommentedVar = 123 " `; exports[`addEnvVar addEnvVar adds environment variables as part of a setup task should handle existing environment variables with quoted values and no spacing 1`] = ` "EXISTING_VAR="value" # CommentedVar=123 " `; exports[`updateTomlConfig updateTomlConfig configures a new CLI plugin adds package but keeps autoInstall false 1`] = ` "[web] title = "Redwood App" port = 8_910 apiUrl = "/.redwood/functions" includeEnvironmentVariables = [ ] [api] port = 8_911 [experimental.cli] autoInstall = false [[experimental.cli.plugins]] package = "@example/test-package-when-autoInstall-false" enabled = true " `; exports[`updateTomlConfig updateTomlConfig configures a new CLI plugin adds when experimental cli has some plugins configured 1`] = ` "[web] title = "Redwood App" port = 8_910 apiUrl = "/.redwood/functions" includeEnvironmentVariables = [ ] [api] port = 8_911 [experimental.cli] autoInstall = true [[experimental.cli.plugins]] package = "@existing-example/some-package-when-cli-has-some-packages-configured" [[experimental.cli.plugins]] package = "@example/test-package-name" enabled = true " `; exports[`updateTomlConfig updateTomlConfig configures a new CLI plugin adds when experimental cli is not configured 1`] = ` "[web] title = "Redwood App" port = 8_910 apiUrl = "/.redwood/functions" includeEnvironmentVariables = [ ] [api] port = 8_911 [experimental.cli] autoInstall = true [[experimental.cli.plugins]] package = "@example/test-package-when-cli-not-configured" enabled = true " `; exports[`updateTomlConfig updateTomlConfig configures a new CLI plugin adds when experimental cli is setup but has no plugins configured 1`] = ` "[web] title = "Redwood App" port = 8_910 apiUrl = "/.redwood/functions" includeEnvironmentVariables = [ ] [api] port = 8_911 [experimental.cli] autoInstall = true [[experimental.cli.plugins]] package = "@example/test-package-when-no-plugins-configured" enabled = true " `; exports[`updateTomlConfig updateTomlConfig configures a new CLI plugin does not add duplicate place when experimental cli has that plugin configured 1`] = ` "[web] title = "Redwood App" port = 8_910 apiUrl = "/.redwood/functions" includeEnvironmentVariables = [ ] [api] port = 8_911 [experimental.cli] autoInstall = true [[experimental.cli.plugins]] package = "@existing-example/some-package-name-already-exists" " `;
4,551
0
petrpan-code/redwoodjs/redwood/packages/cli-packages
petrpan-code/redwoodjs/redwood/packages/cli-packages/dataMigrate/dist.test.ts
import fs from 'fs' import path from 'path' const distPath = path.join(__dirname, 'dist') describe('dist', () => { it("shouldn't have tests", () => { expect(fs.existsSync(path.join(distPath, '__tests__'))).toBe(false) }) it("shouldn't have the types file", () => { expect(fs.existsSync(path.join(distPath, 'types.ts'))).toBe(false) expect(fs.existsSync(path.join(distPath, 'types.js'))).toBe(false) }) it('should export commands', async () => { const mod = await import(path.join(distPath, 'index.js')) expect(mod).toHaveProperty('commands') }) describe('bin', () => { it('starts with shebang', () => { const binFileContent = fs.readFileSync( path.join(distPath, 'bin.js'), 'utf-8' ) binFileContent.startsWith('#!/usr/bin/env node') }) }) })
4,558
0
petrpan-code/redwoodjs/redwood/packages/cli-packages/dataMigrate/src
petrpan-code/redwoodjs/redwood/packages/cli-packages/dataMigrate/src/__tests__/install.test.ts
import * as installCommand from '../commands/install' import { handler as dataMigrateInstallHandler } from '../commands/installHandler.js' jest.mock( '../commands/installHandler.js', () => ({ handler: jest.fn(), }), { virtual: true } ) describe('install', () => { it('exports `command`, `description`, `builder`, and `handler`', () => { for (const property of ['command', 'builder', 'description', 'handler']) { expect(installCommand).toHaveProperty(property) } }) it("`command` and `description` haven't unintentionally changed", () => { expect(installCommand.command).toMatchInlineSnapshot(`"install"`) expect(installCommand.description).toMatchInlineSnapshot( `"Add the RW_DataMigration model to your schema"` ) }) it('`builder` has an epilogue', () => { const yargs = { epilogue: jest.fn() } // @ts-expect-error this is a test file; epilogue is the only thing `builder` calls right now installCommand.builder(yargs) expect(yargs.epilogue).toBeCalledWith( // eslint-disable-next-line no-irregular-whitespace 'Also see the Redwood CLI Reference (​https://redwoodjs.com/docs/cli-commands#datamigrate-install​)' ) }) it('`handler` proxies to `./installHandler.js`', async () => { await installCommand.handler() expect(dataMigrateInstallHandler).toHaveBeenCalled() }) })
4,559
0
petrpan-code/redwoodjs/redwood/packages/cli-packages/dataMigrate/src
petrpan-code/redwoodjs/redwood/packages/cli-packages/dataMigrate/src/__tests__/installHandler.test.ts
import fs from 'fs' import execa from 'execa' import { vol } from 'memfs' import { getPaths } from '@redwoodjs/project-config' import { handler, RW_DATA_MIGRATION_MODEL, createDatabaseMigrationCommand, notes, } from '../commands/installHandler' jest.mock('fs', () => require('memfs').fs) jest.mock('execa', () => { return { command: jest.fn(() => { return { stdout: 42, } }), } }) describe('installHandler', () => { it("the RW_DATA_MIGRATION_MODEL hasn't unintentionally changed", () => { expect(RW_DATA_MIGRATION_MODEL).toMatchInlineSnapshot(` "model RW_DataMigration { version String @id name String startedAt DateTime finishedAt DateTime }" `) }) it("the `createDatabaseMigrationCommand` hasn't unintentionally changed", () => { expect(createDatabaseMigrationCommand).toMatchInlineSnapshot( `"yarn rw prisma migrate dev --name create_data_migrations --create-only"` ) }) it('adds a data migrations directory, model, and migration', async () => { const redwoodProjectPath = '/redwood-app' process.env.RWJS_CWD = redwoodProjectPath vol.fromNestedJSON( { 'redwood.toml': '', api: { db: { 'schema.prisma': '', }, }, }, redwoodProjectPath ) console.log = jest.fn() await handler() const dataMigrationsPath = getPaths().api.dataMigrations expect(fs.readdirSync(dataMigrationsPath)).toEqual(['.keep']) expect(fs.readFileSync(getPaths().api.dbSchema, 'utf-8')).toMatch( RW_DATA_MIGRATION_MODEL ) expect(execa.command).toHaveBeenCalledWith(createDatabaseMigrationCommand, { cwd: getPaths().base, }) expect(console.log).toHaveBeenCalledWith(notes) }) })
4,560
0
petrpan-code/redwoodjs/redwood/packages/cli-packages/dataMigrate/src
petrpan-code/redwoodjs/redwood/packages/cli-packages/dataMigrate/src/__tests__/up.test.ts
import { vol } from 'memfs' import yargs from 'yargs/yargs' import { getPaths } from '@redwoodjs/project-config' import * as upCommand from '../commands/up' import { handler as dataMigrateUpHandler } from '../commands/upHandler.js' jest.mock('fs', () => require('memfs').fs) jest.mock( '../commands/upHandler.js', () => ({ handler: jest.fn(), }), { virtual: true } ) describe('up', () => { it('exports `command`, `description`, `builder`, and `handler`', () => { expect(upCommand).toHaveProperty('command', 'up') expect(upCommand).toHaveProperty( 'description', 'Run any outstanding Data Migrations against the database' ) expect(upCommand).toHaveProperty('builder') expect(upCommand).toHaveProperty('handler') }) it('`builder` configures two options with defaults', () => { vol.fromNestedJSON( { 'redwood.toml': '', api: { dist: {}, }, }, '/redwood-app' ) process.env.RWJS_CWD = '/redwood-app' const { argv } = upCommand.builder(yargs) expect(argv).toHaveProperty('import-db-client-from-dist', false) expect(argv).toHaveProperty('dist-path', getPaths().api.dist) }) it('`handler` proxies to `./upHandler.js`', async () => { await upCommand.handler({}) expect(dataMigrateUpHandler).toHaveBeenCalled() }) })
4,561
0
petrpan-code/redwoodjs/redwood/packages/cli-packages/dataMigrate/src
petrpan-code/redwoodjs/redwood/packages/cli-packages/dataMigrate/src/__tests__/upHandler.test.ts
import { vol } from 'memfs' import { getPaths } from '@redwoodjs/project-config' import { handler, NO_PENDING_MIGRATIONS_MESSAGE } from '../commands/upHandler' // ─── Mocks ─────────────────────────────────────────────────────────────────── const redwoodProjectPath = '/redwood-app' jest.mock('fs', () => require('memfs').fs) const mockDataMigrations: { current: any[] } = { current: [] } jest.mock( '/redwood-app/api/dist/lib/db.js', () => { return { db: { rW_DataMigration: { create(dataMigration) { mockDataMigrations.current.push(dataMigration) }, findMany() { return mockDataMigrations.current }, }, $disconnect: () => {}, }, } }, { virtual: true } ) jest.mock( `\\redwood-app\\api\\dist\\lib\\db.js`, () => { return { db: { rW_DataMigration: { create(dataMigration) { mockDataMigrations.current.push(dataMigration) }, findMany() { return mockDataMigrations.current }, }, $disconnect: () => {}, }, } }, { virtual: true } ) jest.mock( '/redwood-app/api/db/dataMigrations/20230822075442-wip.ts', () => { return { default: () => {} } }, { virtual: true, } ) jest.mock( '\\redwood-app\\api\\db\\dataMigrations\\20230822075442-wip.ts', () => { return { default: () => {} } }, { virtual: true, } ) jest.mock( '/redwood-app/api/db/dataMigrations/20230822075443-wip.ts', () => { return { default: () => { throw new Error('oops') }, } }, { virtual: true, } ) jest.mock( '\\redwood-app\\api\\db\\dataMigrations\\20230822075443-wip.ts', () => { return { default: () => { throw new Error('oops') }, } }, { virtual: true, } ) jest.mock( '/redwood-app/api/db/dataMigrations/20230822075444-wip.ts', () => { return { default: () => {} } }, { virtual: true, } ) jest.mock( '\\redwood-app\\api\\db\\dataMigrations\\20230822075444-wip.ts', () => { return { default: () => {} } }, { virtual: true, } ) const RWJS_CWD = process.env.RWJS_CWD beforeAll(() => { process.env.RWJS_CWD = redwoodProjectPath }) afterEach(() => { vol.reset() mockDataMigrations.current = [] }) afterAll(() => { process.env.RWJS_CWD = RWJS_CWD }) const ranDataMigration = { version: '20230822075441', name: '20230822075441-wip.ts', startedAt: '2023-08-22T07:55:16.292Z', finishedAt: '2023-08-22T07:55:16.292Z', } // ─── Tests ─────────────────────────────────────────────────────────────────── describe('upHandler', () => { it("noops if there's no data migrations directory", async () => { console.info = jest.fn() vol.fromNestedJSON( { 'redwood.toml': '', api: { dist: { lib: { 'db.js': '', }, }, db: { // No dataMigrations dir: // // dataMigrations: { // [ranDataMigration.name]: '', // }, }, }, }, redwoodProjectPath ) await handler({ importDbClientFromDist: true, distPath: getPaths().api.dist, }) expect(console.info.mock.calls[0][0]).toMatch(NO_PENDING_MIGRATIONS_MESSAGE) }) it("noops if there's no pending migrations", async () => { mockDataMigrations.current = [ranDataMigration] vol.fromNestedJSON( { 'redwood.toml': '', api: { dist: { lib: { 'db.js': '', }, }, db: { dataMigrations: { [ranDataMigration.name]: '', }, }, }, }, redwoodProjectPath ) console.info = jest.fn() await handler({ importDbClientFromDist: true, distPath: getPaths().api.dist, }) expect(console.info.mock.calls[0][0]).toMatch(NO_PENDING_MIGRATIONS_MESSAGE) }) it('runs pending migrations', async () => { console.info = jest.fn() console.error = jest.fn() console.warn = jest.fn() mockDataMigrations.current = [ { version: '20230822075441', name: '20230822075441-wip.ts', startedAt: '2023-08-22T07:55:16.292Z', finishedAt: '2023-08-22T07:55:16.292Z', }, ] vol.fromNestedJSON( { 'redwood.toml': '', api: { dist: { lib: { 'db.js': '', }, }, db: { dataMigrations: { '20230822075442-wip.ts': '', '20230822075443-wip.ts': '', '20230822075444-wip.ts': '', }, }, }, }, redwoodProjectPath ) await handler({ importDbClientFromDist: true, distPath: getPaths().api.dist, }) expect(console.info.mock.calls[0][0]).toMatch( '1 data migration(s) completed successfully.' ) expect(console.error.mock.calls[1][0]).toMatch( '1 data migration(s) exited with errors.' ) expect(console.warn.mock.calls[0][0]).toMatch( '1 data migration(s) skipped due to previous error' ) }) })
4,721
0
petrpan-code/redwoodjs/redwood/packages/cli/src/commands/generate/component
petrpan-code/redwoodjs/redwood/packages/cli/src/commands/generate/component/__tests__/component.test.ts
globalThis.__dirname = __dirname import path from 'path' import yargs from 'yargs' // Shared mocks for paths, etc. import '../../../../lib/test' import * as component from '../component' let singleWordDefaultFiles, multiWordDefaultFiles, javascriptFiles, typescriptFiles, withoutTestFiles, withoutStoryFiles beforeAll(() => { singleWordDefaultFiles = component.files({ name: 'User', tests: true, stories: true, }) multiWordDefaultFiles = component.files({ name: 'UserProfile', tests: true, stories: true, }) javascriptFiles = component.files({ name: 'JavascriptUser', typescript: false, stories: true, tests: true, }) typescriptFiles = component.files({ name: 'TypescriptUser', typescript: true, stories: true, tests: true, }) withoutTestFiles = component.files({ name: 'withoutTests', javascript: true, stories: true, tests: false, }) withoutStoryFiles = component.files({ name: 'withoutStories', javascript: true, tests: true, stories: false, }) }) test('returns exactly 3 files', () => { expect(Object.keys(singleWordDefaultFiles).length).toEqual(3) }) test('keeps Component in name', () => { const { name } = yargs .command('component <name>', false, component.builder) .parse('component BazingaComponent') expect(name).toEqual('BazingaComponent') }) test('creates a single word component', () => { expect( singleWordDefaultFiles[ path.normalize('/path/to/project/web/src/components/User/User.jsx') ] ).toMatchSnapshot() }) test('creates a single word component test', () => { expect( singleWordDefaultFiles[ path.normalize('/path/to/project/web/src/components/User/User.test.jsx') ] ).toMatchSnapshot() }) test('creates a single word component story', () => { expect( singleWordDefaultFiles[ path.normalize( '/path/to/project/web/src/components/User/User.stories.jsx' ) ] ).toMatchSnapshot() }) test('creates a multi word component', () => { expect( multiWordDefaultFiles[ path.normalize( '/path/to/project/web/src/components/UserProfile/UserProfile.jsx' ) ] ).toMatchSnapshot() }) test('creates a TS component and test', () => { expect( typescriptFiles[ path.normalize( '/path/to/project/web/src/components/TypescriptUser/TypescriptUser.tsx' ) ] ).toMatchSnapshot() expect( typescriptFiles[ path.normalize( '/path/to/project/web/src/components/TypescriptUser/TypescriptUser.test.tsx' ) ] ).toMatchSnapshot() }) test('creates a multi word component test', () => { expect( multiWordDefaultFiles[ path.normalize( '/path/to/project/web/src/components/UserProfile/UserProfile.test.jsx' ) ] ).toMatchSnapshot() }) test('creates a multi word component story', () => { expect( multiWordDefaultFiles[ path.normalize( '/path/to/project/web/src/components/UserProfile/UserProfile.stories.jsx' ) ] ).toMatchSnapshot() }) test('creates JS component files if typescript = false', () => { expect( javascriptFiles[ path.normalize( '/path/to/project/web/src/components/JavascriptUser/JavascriptUser.jsx' ) ] ).not.toBeUndefined() expect( javascriptFiles[ path.normalize( '/path/to/project/web/src/components/JavascriptUser/JavascriptUser.test.jsx' ) ] ).not.toBeUndefined() }) test('creates TS component files if typescript = true', () => { expect( typescriptFiles[ path.normalize( '/path/to/project/web/src/components/TypescriptUser/TypescriptUser.tsx' ) ] ).not.toBeUndefined() expect( typescriptFiles[ path.normalize( '/path/to/project/web/src/components/TypescriptUser/TypescriptUser.test.tsx' ) ] ).not.toBeUndefined() }) test("doesn't include storybook file when --stories is set to false", () => { expect(Object.keys(withoutStoryFiles)).toEqual([ path.normalize( '/path/to/project/web/src/components/WithoutStories/WithoutStories.test.jsx' ), path.normalize( '/path/to/project/web/src/components/WithoutStories/WithoutStories.jsx' ), ]) }) test("doesn't include test file when --tests is set to false", () => { expect(Object.keys(withoutTestFiles)).toEqual([ path.normalize( '/path/to/project/web/src/components/WithoutTests/WithoutTests.stories.jsx' ), path.normalize( '/path/to/project/web/src/components/WithoutTests/WithoutTests.jsx' ), ]) })
4,722
0
petrpan-code/redwoodjs/redwood/packages/cli/src/commands/generate/component/__tests__
petrpan-code/redwoodjs/redwood/packages/cli/src/commands/generate/component/__tests__/__snapshots__/component.test.ts.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`creates a TS component and test 1`] = ` "const TypescriptUser = () => { return ( <div> <h2>{'TypescriptUser'}</h2> <p> {'Find me in ./web/src/components/TypescriptUser/TypescriptUser.tsx'} </p> </div> ) } export default TypescriptUser " `; exports[`creates a TS component and test 2`] = ` "import { render } from '@redwoodjs/testing/web' import TypescriptUser from './TypescriptUser' // Improve this test with help from the Redwood Testing Doc: // https://redwoodjs.com/docs/testing#testing-components describe('TypescriptUser', () => { it('renders successfully', () => { expect(() => { render(<TypescriptUser />) }).not.toThrow() }) }) " `; exports[`creates a multi word component 1`] = ` "const UserProfile = () => { return ( <div> <h2>{'UserProfile'}</h2> <p>{'Find me in ./web/src/components/UserProfile/UserProfile.jsx'}</p> </div> ) } export default UserProfile " `; exports[`creates a multi word component story 1`] = ` "// Pass props to your component by passing an \`args\` object to your story // // \`\`\`jsx // export const Primary = { // args: { // propName: propValue // } // } // \`\`\` // // See https://storybook.js.org/docs/react/writing-stories/args. import UserProfile from './UserProfile' export default { component: UserProfile } export const Primary = {} " `; exports[`creates a multi word component test 1`] = ` "import { render } from '@redwoodjs/testing/web' import UserProfile from './UserProfile' // Improve this test with help from the Redwood Testing Doc: // https://redwoodjs.com/docs/testing#testing-components describe('UserProfile', () => { it('renders successfully', () => { expect(() => { render(<UserProfile />) }).not.toThrow() }) }) " `; exports[`creates a single word component 1`] = ` "const User = () => { return ( <div> <h2>{'User'}</h2> <p>{'Find me in ./web/src/components/User/User.jsx'}</p> </div> ) } export default User " `; exports[`creates a single word component story 1`] = ` "// Pass props to your component by passing an \`args\` object to your story // // \`\`\`jsx // export const Primary = { // args: { // propName: propValue // } // } // \`\`\` // // See https://storybook.js.org/docs/react/writing-stories/args. import User from './User' export default { component: User } export const Primary = {} " `; exports[`creates a single word component test 1`] = ` "import { render } from '@redwoodjs/testing/web' import User from './User' // Improve this test with help from the Redwood Testing Doc: // https://redwoodjs.com/docs/testing#testing-components describe('User', () => { it('renders successfully', () => { expect(() => { render(<User />) }).not.toThrow() }) }) " `;
4,726
0
petrpan-code/redwoodjs/redwood/packages/cli/src/commands/generate/component
petrpan-code/redwoodjs/redwood/packages/cli/src/commands/generate/component/templates/test.tsx.template
import { render } from '@redwoodjs/testing/web' import ${pascalName} from './${pascalName}' // Improve this test with help from the Redwood Testing Doc: // https://redwoodjs.com/docs/testing#testing-components describe('${pascalName}', () => { it('renders successfully', () => { expect(() => { render(<${pascalName} />) }).not.toThrow() }) })
4,741
0
petrpan-code/redwoodjs/redwood/packages/cli/src/commands/generate/directive
petrpan-code/redwoodjs/redwood/packages/cli/src/commands/generate/directive/__tests__/directive.test.ts
globalThis.__dirname = __dirname // Load shared mocks import '../../../../lib/test' import path from 'path' import yargs from 'yargs' import * as directive from '../directive' test('creates a JavaScript validator directive', () => { const output = directive.files({ name: 'require-admin', // checking camel casing too! typescript: false, tests: true, type: 'validator', }) const expectedOutputPath = path.normalize( '/path/to/project/api/src/directives/requireAdmin/requireAdmin.js' ) const expectedTestOutputPath = path.normalize( '/path/to/project/api/src/directives/requireAdmin/requireAdmin.test.js' ) expect(Object.keys(output)).toContainEqual(expectedOutputPath) expect(Object.keys(output)).toContainEqual(expectedTestOutputPath) expect(output[expectedOutputPath]).toMatchSnapshot('js directive') expect(output[expectedTestOutputPath]).toMatchSnapshot('js directive test') }) test('creates a TypeScript transformer directive', () => { const output = directive.files({ name: 'bazinga-foo_bar', // checking camel casing too! typescript: true, tests: true, type: 'transformer', }) const expectedOutputPath = path.normalize( '/path/to/project/api/src/directives/bazingaFooBar/bazingaFooBar.ts' ) const expectedTestOutputPath = path.normalize( '/path/to/project/api/src/directives/bazingaFooBar/bazingaFooBar.test.ts' ) expect(Object.keys(output)).toContainEqual(expectedOutputPath) expect(Object.keys(output)).toContainEqual(expectedTestOutputPath) expect(output[expectedOutputPath]).toMatchSnapshot('ts directive') expect(output[expectedTestOutputPath]).toMatchSnapshot('ts directive test') }) test('keeps Directive in name', () => { const { name } = yargs .command('directive <name>', false, directive.builder) .parse('directive BazingaDirective') expect(name).toEqual('BazingaDirective') })
4,742
0
petrpan-code/redwoodjs/redwood/packages/cli/src/commands/generate/directive/__tests__
petrpan-code/redwoodjs/redwood/packages/cli/src/commands/generate/directive/__tests__/__snapshots__/directive.test.ts.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`creates a JavaScript validator directive: js directive 1`] = ` "import { createValidatorDirective } from '@redwoodjs/graphql-server' import { logger } from 'src/lib/logger' export const schema = gql\` """ Use @requireAdmin to validate access to a field, query or mutation. """ directive @requireAdmin on FIELD_DEFINITION \` const validate = ({ context, directiveArgs }) => { /** * Write your validation logic inside this function. * Validator directives do not have access to the field value, i.e. they are called before resolving the value * * - Throw an error, if you want to stop executing e.g. not sufficient permissions * - Validator directives can be async or sync * - Returned value will be ignored */ // currentUser is only available when auth is setup. logger.debug( { currentUser: context.currentUser }, 'currentUser in requireAdmin directive' ) // You can also modify your directive to take arguments // and use the directiveArgs object provided to this function to get values // See documentation here: https://redwoodjs.com/docs/directives logger.debug(directiveArgs, 'directiveArgs in requireAdmin directive') throw new Error('Implementation missing for requireAdmin') } const requireAdmin = createValidatorDirective(schema, validate) export default requireAdmin " `; exports[`creates a JavaScript validator directive: js directive test 1`] = ` "import { mockRedwoodDirective, getDirectiveName } from '@redwoodjs/testing/api' import requireAdmin from './requireAdmin' describe('requireAdmin directive', () => { it('declares the directive sdl as schema, with the correct name', () => { expect(requireAdmin.schema).toBeTruthy() expect(getDirectiveName(requireAdmin.schema)).toBe('requireAdmin') }) it('has a requireAdmin throws an error if validation does not pass', () => { const mockExecution = mockRedwoodDirective(requireAdmin, {}) expect(mockExecution).toThrowError( 'Implementation missing for requireAdmin' ) }) }) " `; exports[`creates a TypeScript transformer directive: ts directive 1`] = ` "import { createTransformerDirective, TransformerDirectiveFunc, } from '@redwoodjs/graphql-server' import { logger } from 'src/lib/logger' export const schema = gql\` """ Use @bazingaFooBar to transform the resolved value to return a modified result. """ directive @bazingaFooBar on FIELD_DEFINITION \` const transform: TransformerDirectiveFunc = ({ context, resolvedValue }) => { /** * Write your transformation logic inside this function. * Transformer directives run **after** resolving the value * * - You can also throw an error, if you want to stop executing, but note that the value has already been resolved * - Transformer directives **must** be synchronous, and return a value **/ // currentUser is only available when auth is setup. logger.debug( { currentUser: context.currentUser }, 'currentUser in bazingaFooBar directive' ) // ... you can modify the resolvedValue and return it logger.debug(resolvedValue, 'resolvedValue in bazingaFooBar directive') // You can also modify your directive to take arguments // and use the directiveArgs object provided to this function to get values // See documentation here: https://redwoodjs.com/docs/directives return resolvedValue.replace('foo', 'bar') } const bazingaFooBar = createTransformerDirective(schema, transform) export default bazingaFooBar " `; exports[`creates a TypeScript transformer directive: ts directive test 1`] = ` "import { mockRedwoodDirective, getDirectiveName } from '@redwoodjs/testing/api' import bazingaFooBar from './bazingaFooBar' describe('bazingaFooBar directive', () => { it('declares the directive sdl as schema, with the correct name', () => { expect(bazingaFooBar.schema).toBeTruthy() expect(getDirectiveName(bazingaFooBar.schema)).toBe('bazingaFooBar') }) it('has a bazingaFooBar implementation transforms the value', () => { const mockExecution = mockRedwoodDirective(bazingaFooBar, { mockedResolvedValue: 'foo', }) expect(mockExecution()).toBe('bar') }) }) " `;
4,743
0
petrpan-code/redwoodjs/redwood/packages/cli/src/commands/generate/directive
petrpan-code/redwoodjs/redwood/packages/cli/src/commands/generate/directive/templates/transformer.directive.test.ts.template
import { mockRedwoodDirective, getDirectiveName } from '@redwoodjs/testing/api' import ${camelName} from './${camelName}' describe('${camelName} directive', () => { it('declares the directive sdl as schema, with the correct name', () => { expect(${camelName}.schema).toBeTruthy() expect(getDirectiveName(${camelName}.schema)).toBe('${camelName}') }) it('has a ${camelName} implementation transforms the value', () => { const mockExecution = mockRedwoodDirective(${camelName}, { mockedResolvedValue: 'foo', }) expect(mockExecution()).toBe('bar') }) })
4,745
0
petrpan-code/redwoodjs/redwood/packages/cli/src/commands/generate/directive
petrpan-code/redwoodjs/redwood/packages/cli/src/commands/generate/directive/templates/validator.directive.test.ts.template
import { mockRedwoodDirective, getDirectiveName } from '@redwoodjs/testing/api' import ${camelName} from './${camelName}' describe('${camelName} directive', () => { it('declares the directive sdl as schema, with the correct name', () => { expect(${camelName}.schema).toBeTruthy() expect(getDirectiveName(${camelName}.schema)).toBe('${camelName}') }) it('has a ${camelName} throws an error if validation does not pass', () => { const mockExecution = mockRedwoodDirective(${camelName}, {}) expect(mockExecution).toThrowError('Implementation missing for ${camelName}') }) })
4,748
0
petrpan-code/redwoodjs/redwood/packages/cli/src/commands/generate/function
petrpan-code/redwoodjs/redwood/packages/cli/src/commands/generate/function/__tests__/function.test.ts
globalThis.__dirname = __dirname // Load shared mocks import '../../../../lib/test' import path from 'path' import yargs from 'yargs' import * as functionGenerator from '../function' // Should be refactored as it's repeated type WordFilesType = { [key: string]: string } describe('Single word default files', () => { const singleWordDefaultFiles: WordFilesType = functionGenerator.files({ name: 'foo', tests: true, }) it('returns tests, scenario and function file', () => { const fileNames = Object.keys(singleWordDefaultFiles) expect(fileNames.length).toEqual(3) expect(fileNames).toEqual( expect.arrayContaining([ expect.stringContaining('foo.js'), expect.stringContaining('foo.test.js'), expect.stringContaining('foo.scenarios.js'), ]) ) }) it('creates a single word function file', () => { expect( singleWordDefaultFiles[ path.normalize('/path/to/project/api/src/functions/foo/foo.js') ] ).toMatchSnapshot() expect( singleWordDefaultFiles[ path.normalize('/path/to/project/api/src/functions/foo/foo.test.js') ] ).toMatchSnapshot('Test snapshot') expect( singleWordDefaultFiles[ path.normalize( '/path/to/project/api/src/functions/foo/foo.scenarios.js' ) ] ).toMatchSnapshot('Scenario snapshot') }) }) test('Keeps Function in name', () => { // @ts-expect-error Not sure how to pass generic to yargs here const { name } = yargs .command('function <name>', false, functionGenerator.builder) .parse('function BazingaFunction') expect(name).toEqual('BazingaFunction') }) test('creates a multi word function file', () => { const multiWordDefaultFiles = functionGenerator.files({ name: 'send-mail', }) expect( multiWordDefaultFiles[ path.normalize('/path/to/project/api/src/functions/sendMail/sendMail.js') ] ).toMatchSnapshot() }) test('creates a .js file if --javascript=true', () => { const javascriptFiles = functionGenerator.files({ name: 'javascript-function', }) expect( javascriptFiles[ path.normalize( '/path/to/project/api/src/functions/javascriptFunction/javascriptFunction.js' ) ] ).toMatchSnapshot() // ^ JS-function-args should be stripped of their types and consequently the unused 'aws-lamda' import removed. // https://babeljs.io/docs/en/babel-plugin-transform-typescript }) test('creates a .ts file if --typescript=true', () => { const typescriptFiles = functionGenerator.files({ name: 'typescript-function', typescript: true, }) const fileNames = Object.keys(typescriptFiles) expect(fileNames.length).toEqual(3) expect(fileNames).toEqual( expect.arrayContaining([ expect.stringContaining('typescriptFunction.ts'), expect.stringContaining('typescriptFunction.test.ts'), expect.stringContaining('typescriptFunction.scenarios.ts'), ]) ) expect( typescriptFiles[ path.normalize( '/path/to/project/api/src/functions/typescriptFunction/typescriptFunction.ts' ) ] ).toMatchSnapshot() // ^ TS-functions, on the other hand, retain the 'aws-lamda' import and type-declartions. })
4,749
0
petrpan-code/redwoodjs/redwood/packages/cli/src/commands/generate/function/__tests__
petrpan-code/redwoodjs/redwood/packages/cli/src/commands/generate/function/__tests__/__snapshots__/function.test.ts.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`Single word default files creates a single word function file 1`] = ` "import { logger } from 'src/lib/logger' /** * The handler function is your code that processes http request events. * You can use return and throw to send a response or error, respectively. * * Important: When deployed, a custom serverless function is an open API endpoint and * is your responsibility to secure appropriately. * * @see {@link https://redwoodjs.com/docs/serverless-functions#security-considerations|Serverless Function Considerations} * in the RedwoodJS documentation for more information. * * @typedef { import('aws-lambda').APIGatewayEvent } APIGatewayEvent * @typedef { import('aws-lambda').Context } Context * @param { APIGatewayEvent } event - an object which contains information from the invoker. * @param { Context } context - contains information about the invocation, * function, and execution environment. */ export const handler = async (event, _context) => { logger.info(\`\${event.httpMethod} \${event.path}: foo function\`) return { statusCode: 200, headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ data: 'foo function', }), } } " `; exports[`Single word default files creates a single word function file: Scenario snapshot 1`] = ` "export const standard = defineScenario({ // Define the "fixture" to write into your test database here // See guide: https://redwoodjs.com/docs/testing#scenarios }) " `; exports[`Single word default files creates a single word function file: Test snapshot 1`] = ` "import { mockHttpEvent } from '@redwoodjs/testing/api' import { handler } from './foo' // Improve this test with help from the Redwood Testing Doc: // https://redwoodjs.com/docs/testing#testing-functions describe('foo function', () => { it('Should respond with 200', async () => { const httpEvent = mockHttpEvent({ queryStringParameters: { id: '42', // Add parameters here }, }) const response = await handler(httpEvent, null) const { data } = JSON.parse(response.body) expect(response.statusCode).toBe(200) expect(data).toBe('foo function') }) // You can also use scenarios to test your api functions // See guide here: https://redwoodjs.com/docs/testing#scenarios // // scenario('Scenario test', async () => { // // }) }) " `; exports[`creates a .js file if --javascript=true 1`] = ` "import { logger } from 'src/lib/logger' /** * The handler function is your code that processes http request events. * You can use return and throw to send a response or error, respectively. * * Important: When deployed, a custom serverless function is an open API endpoint and * is your responsibility to secure appropriately. * * @see {@link https://redwoodjs.com/docs/serverless-functions#security-considerations|Serverless Function Considerations} * in the RedwoodJS documentation for more information. * * @typedef { import('aws-lambda').APIGatewayEvent } APIGatewayEvent * @typedef { import('aws-lambda').Context } Context * @param { APIGatewayEvent } event - an object which contains information from the invoker. * @param { Context } context - contains information about the invocation, * function, and execution environment. */ export const handler = async (event, _context) => { logger.info(\`\${event.httpMethod} \${event.path}: javascriptFunction function\`) return { statusCode: 200, headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ data: 'javascriptFunction function', }), } } " `; exports[`creates a .ts file if --typescript=true 1`] = ` "import type { APIGatewayEvent, Context } from 'aws-lambda' import { logger } from 'src/lib/logger' /** * The handler function is your code that processes http request events. * You can use return and throw to send a response or error, respectively. * * Important: When deployed, a custom serverless function is an open API endpoint and * is your responsibility to secure appropriately. * * @see {@link https://redwoodjs.com/docs/serverless-functions#security-considerations|Serverless Function Considerations} * in the RedwoodJS documentation for more information. * * @typedef { import('aws-lambda').APIGatewayEvent } APIGatewayEvent * @typedef { import('aws-lambda').Context } Context * @param { APIGatewayEvent } event - an object which contains information from the invoker. * @param { Context } context - contains information about the invocation, * function, and execution environment. */ export const handler = async (event: APIGatewayEvent, _context: Context) => { logger.info(\`\${event.httpMethod} \${event.path}: typescriptFunction function\`) return { statusCode: 200, headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ data: 'typescriptFunction function', }), } } " `; exports[`creates a multi word function file 1`] = ` "import { logger } from 'src/lib/logger' /** * The handler function is your code that processes http request events. * You can use return and throw to send a response or error, respectively. * * Important: When deployed, a custom serverless function is an open API endpoint and * is your responsibility to secure appropriately. * * @see {@link https://redwoodjs.com/docs/serverless-functions#security-considerations|Serverless Function Considerations} * in the RedwoodJS documentation for more information. * * @typedef { import('aws-lambda').APIGatewayEvent } APIGatewayEvent * @typedef { import('aws-lambda').Context } Context * @param { APIGatewayEvent } event - an object which contains information from the invoker. * @param { Context } context - contains information about the invocation, * function, and execution environment. */ export const handler = async (event, _context) => { logger.info(\`\${event.httpMethod} \${event.path}: sendMail function\`) return { statusCode: 200, headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ data: 'sendMail function', }), } } " `;
4,752
0
petrpan-code/redwoodjs/redwood/packages/cli/src/commands/generate/function
petrpan-code/redwoodjs/redwood/packages/cli/src/commands/generate/function/templates/test.ts.template
import { mockHttpEvent } from '@redwoodjs/testing/api' import { handler } from './${name}' // Improve this test with help from the Redwood Testing Doc: // https://redwoodjs.com/docs/testing#testing-functions describe('${name} function', () => { it('Should respond with 200', async () => { const httpEvent = mockHttpEvent({ queryStringParameters: { id: '42', // Add parameters here }, }) const response = await handler(httpEvent, null) const { data } = JSON.parse(response.body) expect(response.statusCode).toBe(200) expect(data).toBe('${name} function') }) // You can also use scenarios to test your api functions // See guide here: https://redwoodjs.com/docs/testing#scenarios // // scenario('Scenario test', async () => { // // }) })
4,754
0
petrpan-code/redwoodjs/redwood/packages/cli/src/commands/generate/layout
petrpan-code/redwoodjs/redwood/packages/cli/src/commands/generate/layout/__tests__/layout.test.ts
globalThis.__dirname = __dirname import path from 'path' // Load shared mocks import '../../../../lib/test' import * as layout from '../layout' describe('Single Word default files', () => { const singleWordDefaultFiles = layout.files({ name: 'App', tests: true, stories: true, }) it('returns exactly 3 files', () => { expect(Object.keys(singleWordDefaultFiles).length).toEqual(3) }) it('creates a single word layout component', () => { expect( singleWordDefaultFiles[ path.normalize( '/path/to/project/web/src/layouts/AppLayout/AppLayout.jsx' ) ] ).toMatchSnapshot() }) it('creates a single word layout test', () => { expect( singleWordDefaultFiles[ path.normalize( '/path/to/project/web/src/layouts/AppLayout/AppLayout.test.jsx' ) ] ).toMatchSnapshot() }) test('creates a single word layout stories', () => { expect( singleWordDefaultFiles[ path.normalize( '/path/to/project/web/src/layouts/AppLayout/AppLayout.stories.jsx' ) ] ).toMatchSnapshot() }) }) describe('Multi word default files', () => { const multiWordDefaultFiles = layout.files({ name: 'SinglePage', tests: true, stories: true, }) it('creates a multi word layout component', () => { expect( multiWordDefaultFiles[ path.normalize( '/path/to/project/web/src/layouts/SinglePageLayout/SinglePageLayout.jsx' ) ] ).toMatchSnapshot() }) it('creates a multi word layout test', () => { expect( multiWordDefaultFiles[ path.normalize( '/path/to/project/web/src/layouts/SinglePageLayout/SinglePageLayout.test.jsx' ) ] ).toMatchSnapshot() }) it('creates a multi word layout test', () => { expect( multiWordDefaultFiles[ path.normalize( '/path/to/project/web/src/layouts/SinglePageLayout/SinglePageLayout.stories.jsx' ) ] ).toMatchSnapshot() }) }) describe('JS Files', () => { const javascriptFiles = layout.files({ name: 'JavascriptPage', javascript: true, tests: true, stories: true, }) it('creates JS layout components if javascript = true', () => { expect( javascriptFiles[ path.normalize( '/path/to/project/web/src/layouts/JavascriptPageLayout/JavascriptPageLayout.jsx' ) ] ).not.toBeUndefined() expect( javascriptFiles[ path.normalize( '/path/to/project/web/src/layouts/JavascriptPageLayout/JavascriptPageLayout.test.jsx' ) ] ).not.toBeUndefined() }) }) test('trims Layout from end of name', () => { const files = layout.files({ name: 'BazingaLayout', tests: true, stories: true, }) const layoutCode = files[ path.normalize( '/path/to/project/web/src/layouts/BazingaLayout/BazingaLayout.jsx' ) ] expect(layoutCode).not.toBeUndefined() expect( layoutCode.split('\n').includes('export default BazingaLayout') ).toBeTruthy() }) test('Does not trim Layout from beginning of name', () => { const files = layout.files({ name: 'LayoutForBazinga', tests: true, stories: true, }) const layoutCode = files[ path.normalize( '/path/to/project/web/src/layouts/LayoutForBazingaLayout/LayoutForBazingaLayout.jsx' ) ] expect(layoutCode).not.toBeUndefined() expect( layoutCode.split('\n').includes('export default LayoutForBazingaLayout') ).toBeTruthy() }) test('Does not trim Layout from middle of name', () => { const files = layout.files({ name: 'MyLayoutForBazinga', tests: true, stories: true, }) const layoutCode = files[ path.normalize( '/path/to/project/web/src/layouts/MyLayoutForBazingaLayout/MyLayoutForBazingaLayout.jsx' ) ] expect(layoutCode).not.toBeUndefined() expect( layoutCode.split('\n').includes('export default MyLayoutForBazingaLayout') ).toBeTruthy() }) test('Only trims Layout once', () => { const files = layout.files({ name: 'BazingaLayoutLayout', tests: true, stories: true, }) const layoutCode = files[ path.normalize( '/path/to/project/web/src/layouts/BazingaLayoutLayout/BazingaLayoutLayout.jsx' ) ] expect(layoutCode).not.toBeUndefined() expect( layoutCode.split('\n').includes('export default BazingaLayoutLayout') ).toBeTruthy() }) describe('TS files', () => { const typescriptFiles = layout.files({ name: 'TypescriptPage', typescript: true, tests: true, stories: true, }) it('creates TS layout components if typescript = true', () => { expect( typescriptFiles[ path.normalize( '/path/to/project/web/src/layouts/TypescriptPageLayout/TypescriptPageLayout.tsx' ) ] ).not.toBeUndefined() expect( typescriptFiles[ path.normalize( '/path/to/project/web/src/layouts/TypescriptPageLayout/TypescriptPageLayout.test.tsx' ) ] ).not.toBeUndefined() }) }) test("doesn't include storybook file when --stories is set to false", () => { const withoutStoryFiles = layout.files({ name: 'withoutStories', javascript: true, tests: true, stories: false, }) expect(Object.keys(withoutStoryFiles)).toEqual([ path.normalize( '/path/to/project/web/src/layouts/WithoutStoriesLayout/WithoutStoriesLayout.test.jsx' ), path.normalize( '/path/to/project/web/src/layouts/WithoutStoriesLayout/WithoutStoriesLayout.jsx' ), ]) }) test("doesn't include test file when --tests is set to false", () => { const withoutTestFiles = layout.files({ name: 'withoutTests', tests: false, stories: true, }) expect(Object.keys(withoutTestFiles)).toEqual([ path.normalize( '/path/to/project/web/src/layouts/WithoutTestsLayout/WithoutTestsLayout.stories.jsx' ), path.normalize( '/path/to/project/web/src/layouts/WithoutTestsLayout/WithoutTestsLayout.jsx' ), ]) }) test('JavaScript: includes skip link when --skipLink is set to true', () => { const withSkipLinkFilesJS = layout.files({ name: 'A11y', skipLink: true, }) expect( withSkipLinkFilesJS[ path.normalize( '/path/to/project/web/src/layouts/A11yLayout/A11yLayout.jsx' ) ] ).toMatchSnapshot() }) test('TypeScript: includes skip link when --skipLink is set to true', () => { const withSkipLinkFilesTS = layout.files({ name: 'A11y', skipLink: true, typescript: true, }) expect( withSkipLinkFilesTS[ path.normalize( '/path/to/project/web/src/layouts/A11yLayout/A11yLayout.tsx' ) ] ).toMatchSnapshot() })
4,755
0
petrpan-code/redwoodjs/redwood/packages/cli/src/commands/generate/layout/__tests__
petrpan-code/redwoodjs/redwood/packages/cli/src/commands/generate/layout/__tests__/__snapshots__/layout.test.ts.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`JavaScript: includes skip link when --skipLink is set to true 1`] = ` "import { SkipNavLink, SkipNavContent } from '@redwoodjs/router' import '@reach/skip-nav/styles.css' /** * since the main content isn't usually the first thing in the document, * it's important to provide a shortcut for keyboard and screen-reader users to skip to the main content * API docs: https://reach.tech/skip-nav/#reach-skip-nav */ const A11yLayout = ({ children }) => { return ( <> {/* renders a link that remains hidden till focused; put it at the top of your layout */} <SkipNavLink /> <nav></nav> {/* renders a div as the target for the link; put it next to your main content */} <SkipNavContent /> <main>{children}</main> </> ) } export default A11yLayout " `; exports[`Multi word default files creates a multi word layout component 1`] = ` "const SinglePageLayout = ({ children }) => { return <>{children}</> } export default SinglePageLayout " `; exports[`Multi word default files creates a multi word layout test 1`] = ` "import { render } from '@redwoodjs/testing/web' import SinglePageLayout from './SinglePageLayout' // Improve this test with help from the Redwood Testing Doc: // https://redwoodjs.com/docs/testing#testing-pages-layouts describe('SinglePageLayout', () => { it('renders successfully', () => { expect(() => { render(<SinglePageLayout />) }).not.toThrow() }) }) " `; exports[`Multi word default files creates a multi word layout test 2`] = ` "import SinglePageLayout from './SinglePageLayout' const meta = { component: SinglePageLayout, } export default meta export const Primary = {} " `; exports[`Single Word default files creates a single word layout component 1`] = ` "const AppLayout = ({ children }) => { return <>{children}</> } export default AppLayout " `; exports[`Single Word default files creates a single word layout stories 1`] = ` "import AppLayout from './AppLayout' const meta = { component: AppLayout, } export default meta export const Primary = {} " `; exports[`Single Word default files creates a single word layout test 1`] = ` "import { render } from '@redwoodjs/testing/web' import AppLayout from './AppLayout' // Improve this test with help from the Redwood Testing Doc: // https://redwoodjs.com/docs/testing#testing-pages-layouts describe('AppLayout', () => { it('renders successfully', () => { expect(() => { render(<AppLayout />) }).not.toThrow() }) }) " `; exports[`TypeScript: includes skip link when --skipLink is set to true 1`] = ` "import { SkipNavLink, SkipNavContent } from '@redwoodjs/router' import '@reach/skip-nav/styles.css' /** * since the main content isn't usually the first thing in the document, * it's important to provide a shortcut for keyboard and screen-reader users to skip to the main content * API docs: https://reach.tech/skip-nav/#reach-skip-nav */ type A11yLayoutProps = { children?: React.ReactNode } const A11yLayout = ({ children }: A11yLayoutProps) => { return ( <> {/* renders a link that remains hidden till focused; put it at the top of your layout */} <SkipNavLink /> <nav></nav> {/* renders a div as the target for the link; put it next to your main content */} <SkipNavContent /> <main>{children}</main> </> ) } export default A11yLayout " `;
4,759
0
petrpan-code/redwoodjs/redwood/packages/cli/src/commands/generate/layout
petrpan-code/redwoodjs/redwood/packages/cli/src/commands/generate/layout/templates/test.tsx.template
import { render } from '@redwoodjs/testing/web' import ${pascalName}Layout from './${pascalName}Layout' // Improve this test with help from the Redwood Testing Doc: // https://redwoodjs.com/docs/testing#testing-pages-layouts describe('${pascalName}Layout', () => { it('renders successfully', () => { expect(() => { render(<${pascalName}Layout />) }).not.toThrow() }) })
4,768
0
petrpan-code/redwoodjs/redwood/packages/cli/src/commands/generate/page
petrpan-code/redwoodjs/redwood/packages/cli/src/commands/generate/page/templates/test.tsx.template
import { render } from '@redwoodjs/testing/web' import ${pascalName}Page from './${pascalName}Page' // Improve this test with help from the Redwood Testing Doc: // https://redwoodjs.com/docs/testing#testing-pages-layouts describe('${pascalName}Page', () => { it('renders successfully', () => { expect(() => { render(<${pascalName}Page ${propValueParam}/>) }).not.toThrow() }) })
4,802
0
petrpan-code/redwoodjs/redwood/packages/cli/src/commands/generate/scaffold/templates
petrpan-code/redwoodjs/redwood/packages/cli/src/commands/generate/scaffold/templates/lib/formatters.test.tsx.template
import { render, waitFor, screen } from '@redwoodjs/testing/web' import { formatEnum, jsonTruncate, truncate, timeTag, jsonDisplay, checkboxInputTag, } from './formatters' describe('formatEnum', () => { it('handles nullish values', () => { expect(formatEnum(null)).toEqual('') expect(formatEnum('')).toEqual('') expect(formatEnum(undefined)).toEqual('') }) it('formats a list of values', () => { expect( formatEnum(['RED', 'ORANGE', 'YELLOW', 'GREEN', 'BLUE', 'VIOLET']) ).toEqual('Red, Orange, Yellow, Green, Blue, Violet') }) it('formats a single value', () => { expect(formatEnum('DARK_BLUE')).toEqual('Dark blue') }) it('returns an empty string for values of the wrong type (for JS projects)', () => { // @ts-expect-error - Testing JS scenario expect(formatEnum(5)).toEqual('') }) }) describe('truncate', () => { it('truncates really long strings', () => { expect(truncate('na '.repeat(1000) + 'batman').length).toBeLessThan(1000) expect(truncate('na '.repeat(1000) + 'batman')).not.toMatch(/batman/) }) it('does not modify short strings', () => { expect(truncate('Short strinG')).toEqual('Short strinG') }) it('adds ... to the end of truncated strings', () => { expect(truncate('repeat'.repeat(1000))).toMatch(/\w\.\.\.$/) }) it('accepts numbers', () => { expect(truncate(123)).toEqual('123') expect(truncate(0)).toEqual('0') expect(truncate(0o000)).toEqual('0') }) it('handles arguments of invalid type', () => { // @ts-expect-error - Testing JS scenario expect(truncate(false)).toEqual('false') expect(truncate(undefined)).toEqual('') expect(truncate(null)).toEqual('') }) }) describe('jsonTruncate', () => { it('truncates large json structures', () => { expect( jsonTruncate({ foo: 'foo', bar: 'bar', baz: 'baz', kittens: 'kittens meow', bazinga: 'Sheldon', nested: { foobar: 'I have no imagination', two: 'Second nested item', }, five: 5, bool: false, }) ).toMatch(/.+\n.+\w\.\.\.$/s) }) }) describe('timeTag', () => { it('renders a date', async () => { render(<div>{timeTag(new Date('1970-08-20').toUTCString())}</div>) await waitFor(() => screen.getByText(/1970.*00:00:00/)) }) it('can take an empty input string', async () => { expect(timeTag('')).toEqual('') }) }) describe('jsonDisplay', () => { it('produces the correct output', () => { expect( jsonDisplay({ title: 'TOML Example (but in JSON)', database: { data: [['delta', 'phi'], [3.14]], enabled: true, ports: [8000, 8001, 8002], temp_targets: { case: 72.0, cpu: 79.5, }, }, owner: { dob: '1979-05-27T07:32:00-08:00', name: 'Tom Preston-Werner', }, servers: { alpha: { ip: '10.0.0.1', role: 'frontend', }, beta: { ip: '10.0.0.2', role: 'backend', }, }, }) ).toMatchInlineSnapshot(` <pre> <code> { "title": "TOML Example (but in JSON)", "database": { "data": [ [ "delta", "phi" ], [ 3.14 ] ], "enabled": true, "ports": [ 8000, 8001, 8002 ], "temp_targets": { "case": 72, "cpu": 79.5 } }, "owner": { "dob": "1979-05-27T07:32:00-08:00", "name": "Tom Preston-Werner" }, "servers": { "alpha": { "ip": "10.0.0.1", "role": "frontend" }, "beta": { "ip": "10.0.0.2", "role": "backend" } } } </code> </pre> `) }) }) describe('checkboxInputTag', () => { it('can be checked', () => { render(checkboxInputTag(true)) expect(screen.getByRole('checkbox')).toBeChecked() }) it('can be unchecked', () => { render(checkboxInputTag(false)) expect(screen.getByRole('checkbox')).not.toBeChecked() }) it('is disabled when checked', () => { render(checkboxInputTag(true)) expect(screen.getByRole('checkbox')).toBeDisabled() }) it('is disabled when unchecked', () => { render(checkboxInputTag(false)) expect(screen.getByRole('checkbox')).toBeDisabled() }) })
4,809
0
petrpan-code/redwoodjs/redwood/packages/cli/src/commands/generate/script
petrpan-code/redwoodjs/redwood/packages/cli/src/commands/generate/script/__tests__/script.test.ts
globalThis.__dirname = __dirname // Load shared mocks import '../../../../lib/test' import path from 'path' import yargs from 'yargs' import * as script from '../script' beforeAll(() => {}) test('creates a JavaScript function to execute', () => { const output = script.files({ name: 'scriptyMcScript', typescript: false, }) const expectedOutputPath = path.normalize( '/path/to/project/scripts/scriptyMcScript.js' ) expect(Object.keys(output)).toContainEqual(expectedOutputPath) expect(output[expectedOutputPath]).toMatchSnapshot() }) test('creates a TypeScript function to execute', () => { const output = script.files({ name: 'typescriptyTypescript', typescript: true, }) const expectedOutputPath = path.normalize( '/path/to/project/scripts/typescriptyTypescript.ts' ) const tsconfigPath = path.normalize('/path/to/project/scripts/tsconfig.json') const outputFilePaths = Object.keys(output) expect(outputFilePaths).toContainEqual(expectedOutputPath) expect(output[expectedOutputPath]).toMatchSnapshot() // Should generate tsconfig, because its not present expect(outputFilePaths).toContainEqual(tsconfigPath) }) test('keeps Script in name', () => { const { name } = yargs .command('script <name>', false, script.builder) .parse('script BazingaScript') expect(name).toEqual('BazingaScript') })
4,810
0
petrpan-code/redwoodjs/redwood/packages/cli/src/commands/generate/script/__tests__
petrpan-code/redwoodjs/redwood/packages/cli/src/commands/generate/script/__tests__/__snapshots__/script.test.ts.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`creates a JavaScript function to execute 1`] = ` "// To access your database // Append api/* to import from api and web/* to import from web import { db } from 'api/src/lib/db' export default async ({ args }) => { // Your script here... console.log(':: Executing script with args ::') console.log(args) } " `; exports[`creates a TypeScript function to execute 1`] = ` "// To access your database // Append api/* to import from api and web/* to import from web import { db } from 'api/src/lib/db' export default async ({ args }) => { // Your script here... console.log(':: Executing script with args ::') console.log(args) } " `;
4,828
0
petrpan-code/redwoodjs/redwood/packages/cli/src/commands/generate/service
petrpan-code/redwoodjs/redwood/packages/cli/src/commands/generate/service/templates/test.ts.template
<% // Transforms an object or single value into something that's more suitable // for generating test cases // If a `type` is passed in, the string for creating an object of that type // will be generated // If no type, or a type we don't support, is passed in we'll default to // generating regular strings // Looks for quoted strings, either by single (') or double (") quotes. // When found // - Removes the quotes around `scenario` variables. // - Removes the quotes around `BigInt` fields. const transformValue = (obj, type) => { if (type === 'DateTime') { return `new Date('${obj.toISOString()}')` } else if (type === 'Decimal') { return `new Prisma.Decimal(${obj})` } return JSON.stringify(obj).replace(/['"].*?['"]/g, (string) => { if (string.match(/scenario\./)) { return string.replace(/['"]/g, '') } // BigInt if (string.match(/^\"\d+n\"$/)) { return string.substr(1, string.length - 2) } return string }) } %> <% if (prismaImport) { %>import { Prisma, ${prismaModel} } from '@prisma/client'<% } else { %>import type { ${prismaModel} } from '@prisma/client'<% } %> import { ${pluralCamelName}<% if (crud) { %>,${singularCamelName}, create${singularPascalName}, update${singularPascalName}, delete${singularPascalName}<% } %> } from './${pluralCamelName}' import type { StandardScenario } from './${pluralCamelName}.scenarios' // Generated boilerplate tests do not account for all circumstances // and can fail without adjustments, e.g. Float. // Please refer to the RedwoodJS Testing Docs: // https://redwoodjs.com/docs/testing#testing-services // https://redwoodjs.com/docs/testing#jest-expect-type-considerations describe('${pluralCamelName}', () => { scenario('returns all ${pluralCamelName}', async (scenario: StandardScenario) => { const result = await ${pluralCamelName}() expect(result.length).toEqual(Object.keys(scenario.${singularCamelName}).length) })<% if (crud) { %> scenario('returns a single ${singularCamelName}', async (scenario: StandardScenario) => { const result = await ${singularCamelName}({ id: scenario.${singularCamelName}.one.id }) expect(result).toEqual(scenario.${singularCamelName}.one) }) <% if (create) { %>scenario('creates a ${singularCamelName}', async (${transformValue(create).includes('scenario.') ? 'scenario: StandardScenario' : ''}) => { const result = await create${singularPascalName}({ input: ${transformValue(create)}, }) <% for (const [name, value] of Object.entries(create)) { %> expect(result.${name}).toEqual(${transformValue(value, types[name])})<% } %> })<% } %> <% if (update) { %>scenario('updates a ${singularCamelName}', async (scenario: StandardScenario) => {<% rand = parseInt(Math.random() * 10000000) %> const original = await (${singularCamelName}({ id: scenario.${singularCamelName}.one.id })) as ${prismaModel} const result = await update${singularPascalName}({ id: original.id, input: ${transformValue(update)}, }) <% for (const [name, value] of Object.entries(update)) { %> expect(result.${name}).toEqual(${transformValue(value, types[name])})<% } %> })<% } %> scenario('deletes a ${singularCamelName}', async (scenario: StandardScenario) => { const original = (await delete${singularPascalName}({ id: scenario.${singularCamelName}.one.id })) as ${prismaModel} const result = await ${singularCamelName}({ id: original.id }) expect(result).toEqual(null) })<% } %> })
4,979
0
petrpan-code/redwoodjs/redwood/packages/codemods/src/codemods/v0.37.x/updateApiImports
petrpan-code/redwoodjs/redwood/packages/codemods/src/codemods/v0.37.x/updateApiImports/__tests__/updateApiImports.test.ts
describe('Update API Imports', () => { it('Updates @redwoodjs/api imports', async () => { await matchTransformSnapshot('updateApiImports', 'apiImports') }) })
4,987
0
petrpan-code/redwoodjs/redwood/packages/codemods/src/codemods/v0.37.x/updateForms
petrpan-code/redwoodjs/redwood/packages/codemods/src/codemods/v0.37.x/updateForms/__tests__/updateForms.test.ts
describe('Update Forms', () => { test('Transforms javascript', async () => { await matchTransformSnapshot('updateForms', 'javascript') }) test('Transforms typescript', async () => { await matchTransformSnapshot('updateForms', 'typescript') }) })
4,993
0
petrpan-code/redwoodjs/redwood/packages/codemods/src/codemods/v0.37.x/updateGraphQLFunction
petrpan-code/redwoodjs/redwood/packages/codemods/src/codemods/v0.37.x/updateGraphQLFunction/__tests__/updateGraphQLFunction.test.ts
/** * ts and js are equivalent in this case */ describe('Update GraphQL Function', () => { it('Modifies imports and createGraphQLHandler', async () => { await matchTransformSnapshot('updateGraphQLFunction', 'graphql') }) it('Modifies imports (inline)', async () => { await matchInlineTransformSnapshot( 'updateGraphQLFunction', `import { createGraphQLHandler, makeMergedSchema, } from '@redwoodjs/api'`, `import { createGraphQLHandler } from '@redwoodjs/graphql-server'` ) }) })
5,001
0
petrpan-code/redwoodjs/redwood/packages/codemods/src/codemods/v0.37.x/updateScenarios
petrpan-code/redwoodjs/redwood/packages/codemods/src/codemods/v0.37.x/updateScenarios/__tests__/updateScenarios.test.ts
describe('Update Scenarios', () => { it('Modifies simple Scenarios', async () => { await matchTransformSnapshot('updateScenarios', 'simple') }) it('Modifies more complex Scenarios', async () => { await matchTransformSnapshot('updateScenarios', 'realExample') }) })
5,024
0
petrpan-code/redwoodjs/redwood/packages/codemods/src/codemods/v0.39.x/updateBabelConfig
petrpan-code/redwoodjs/redwood/packages/codemods/src/codemods/v0.39.x/updateBabelConfig/__tests__/updateBabelConfig.test.ts
import transform from '../updateBabelConfig' test('Removes babel config for default setup', async () => { await matchFolderTransform(transform, 'default') }) test('Should preserve custom web config', async () => { // Expecting: // a) .babelrc -> babel.config.js // b) removes "extends" property from config await matchFolderTransform(transform, 'webCustom') }) test('Should throw if root babel.config.js has custom config', async () => { expect(async () => matchFolderTransform(transform, 'rootCustom') ).rejects.toThrowError( 'Cannot automatically codemod your project. Please move your root babel.config.js settings manually' ) })
5,034
0
petrpan-code/redwoodjs/redwood/packages/codemods/src/codemods/v0.39.x/updateCellMocks
petrpan-code/redwoodjs/redwood/packages/codemods/src/codemods/v0.39.x/updateCellMocks/__tests__/updateCellMocks.test.ts
describe('Update cell mocks', () => { test('Converts object mock to a function that returns the object', async () => { await matchTransformSnapshot('updateCellMocks', 'objectCellMock') }) test('Handles Types', async () => { await matchTransformSnapshot('updateCellMocks', 'objectCellMockWithType') }) test('Ignores mocks that are already functions', async () => { await matchTransformSnapshot('updateCellMocks', 'alreadyFunction') }) })
5,057
0
petrpan-code/redwoodjs/redwood/packages/codemods/src/codemods/v0.44.x/updateJestConfig
petrpan-code/redwoodjs/redwood/packages/codemods/src/codemods/v0.44.x/updateJestConfig/__tests__/updateJestConfig.test.ts
import updateJestConfig from '../updateJestConfig' jest.mock('../../../../lib/fetchFileFromTemplate', () => jest.fn((_tag, file) => { if (file === 'jest.config.js') { return [ '// This the Redwood root jest config', '// Each side, e.g. ./web/ and ./api/ has specific config that references this root', '// More info at https://redwoodjs.com/docs/project-configuration-dev-test-build', '', 'module.exports = {', " rootDir: '.',", " projects: ['<rootDir>/{*,!(node_modules)/**/}/jest.config.js'],", '}', ].join('\n') } return [ '// More info at https://redwoodjs.com/docs/project-configuration-dev-test-build', '', 'const config = {', " rootDir: '../',", ` preset: '@redwoodjs/testing/config/jest/${ file.match(/(?<side>api|web)/).groups.side }',`, '}', '', 'module.exports = config', ].join('\n') }) ) jest.setTimeout(25_000) // Skip these tests as these are old codemods // and the tests seem flakey describe.skip('Update Jest Config', () => { it('Adds missing files', async () => { await matchFolderTransform(updateJestConfig, 'missing', { removeWhitespace: true, }) }) it('Keeps custom jest config in api and web', async () => { await matchFolderTransform(updateJestConfig, 'custom', { removeWhitespace: true, }) }) })
5,063
0
petrpan-code/redwoodjs/redwood/packages/codemods/src/codemods/v0.48.x/renameVerifierTimestamp
petrpan-code/redwoodjs/redwood/packages/codemods/src/codemods/v0.48.x/renameVerifierTimestamp/__tests__/renameVerifierTimestamp.test.ts
describe('Rename verifier timestamp option', () => { it('Modifies simple Function', async () => { await matchTransformSnapshot('renameVerifierTimestamp', 'simple') }) })
5,077
0
petrpan-code/redwoodjs/redwood/packages/codemods/src/codemods/v0.50.x/updateDevFatalErrorPage
petrpan-code/redwoodjs/redwood/packages/codemods/src/codemods/v0.50.x/updateDevFatalErrorPage/__tests__/updateDevFatalErrorPage.test.ts
import { updateDevFatalErrorPage } from '../updateDevFatalErrorPage' describe('updateDevFatalErrorPage', () => { it('Replaces the JS FatalErrorPage with a new version that includes development info', async () => { await matchFolderTransform(updateDevFatalErrorPage, 'javascript') }) it('Replaces the TS FatalErrorPage with a new version that includes development info', async () => { await matchFolderTransform(updateDevFatalErrorPage, 'typescript') }) })
5,083
0
petrpan-code/redwoodjs/redwood/packages/codemods/src/codemods/v2.3.x/tsconfigForRouteHooks
petrpan-code/redwoodjs/redwood/packages/codemods/src/codemods/v2.3.x/tsconfigForRouteHooks/__tests__/tsconfigForRouteHooks.test.ts
import addApiAliasToTsConfig from '../tsconfigForRouteHooks' describe('tsconfigForRouteHooks', () => { it('Adds $api to web/tsconfig.json', async () => { await matchFolderTransform(addApiAliasToTsConfig, 'default') }) })
5,089
0
petrpan-code/redwoodjs/redwood/packages/codemods/src/codemods/v2.x.x/configureFastify
petrpan-code/redwoodjs/redwood/packages/codemods/src/codemods/v2.x.x/configureFastify/__tests__/configureFastify.test.ts
describe('configureFastify', () => { it('Converts module.exports to { config }', async () => { await matchTransformSnapshot('configureFastify', 'default') }) })
5,095
0
petrpan-code/redwoodjs/redwood/packages/codemods/src/codemods/v2.x.x/updateResolverTypes
petrpan-code/redwoodjs/redwood/packages/codemods/src/codemods/v2.x.x/updateResolverTypes/__tests__/updateResolverTypes.test.ts
describe('updateResolverTypes', () => { it('Converts PostResolvers to PostRelationResolvers>', async () => { await matchTransformSnapshot('updateResolverTypes', 'default') }) })
5,100
0
petrpan-code/redwoodjs/redwood/packages/codemods/src/codemods/v4.2.x/updateClerkGetCurrentUser
petrpan-code/redwoodjs/redwood/packages/codemods/src/codemods/v4.2.x/updateClerkGetCurrentUser/__tests__/updateClerkGetCurrentUser.test.ts
describe('clerk', () => { it('updates the getCurrentUser function', async () => { await matchTransformSnapshot('updateClerkGetCurrentUser', 'default') }) })
5,108
0
petrpan-code/redwoodjs/redwood/packages/codemods/src/codemods/v4.x.x/useArmor
petrpan-code/redwoodjs/redwood/packages/codemods/src/codemods/v4.x.x/useArmor/__tests__/useArmor.test.ts
describe('useArmor', () => { describe('when depthLimitOptions is not configured in the GraphQL handler', () => { it('makes no changes', async () => { await matchTransformSnapshot('useArmor', 'default') }) }) describe('when depthLimitOptions is configured in the GraphQL handler', () => { it('Modifies depthLimitOptions to use GraphQL Armor settings', async () => { await matchTransformSnapshot('useArmor', 'graphql') }) it('Modifies depthLimitOptions to use GraphQL Armor settings (inline)', async () => { await matchInlineTransformSnapshot( 'useArmor', `import { createGraphQLHandler } from '@redwoodjs/graphql-server' import directives from 'src/directives/**/*.{js,ts}' import sdls from 'src/graphql/**/*.sdl.{js,ts}' import services from 'src/services/**/*.{js,ts}' import { getCurrentUser } from 'src/lib/auth' import { db } from 'src/lib/db' import { logger } from 'src/lib/logger' export const handler = createGraphQLHandler({ getCurrentUser, loggerConfig: { logger, options: {} }, directives, sdls, services, depthLimitOptions: { maxDepth: 42 }, onException: () => { // Disconnect from your database with an unhandled exception. db.$disconnect() }, })`, `import { createGraphQLHandler } from '@redwoodjs/graphql-server' import directives from 'src/directives/**/*.{js,ts}' import sdls from 'src/graphql/**/*.sdl.{js,ts}' import services from 'src/services/**/*.{js,ts}' import { getCurrentUser } from 'src/lib/auth' import { db } from 'src/lib/db' import { logger } from 'src/lib/logger' export const handler = createGraphQLHandler({ getCurrentUser, loggerConfig: { logger, options: {} }, directives, sdls, services, armorConfig: { maxDepth: { n: 42 } }, onException: () => { // Disconnect from your database with an unhandled exception. db.$disconnect() }, })` ) }) }) })
5,126
0
petrpan-code/redwoodjs/redwood/packages/codemods/src/codemods/v5.x.x/cellQueryResult
petrpan-code/redwoodjs/redwood/packages/codemods/src/codemods/v5.x.x/cellQueryResult/__tests__/cellQueryResult.test.ts
describe('cellQueryResult', () => { test('No query result properties used', async () => { await matchTransformSnapshot('cellQueryResult', 'default') }) test('Refetch alone is used', async () => { await matchTransformSnapshot('cellQueryResult', 'refetch') }) test('Client alone is used', async () => { await matchTransformSnapshot('cellQueryResult', 'client') }) test('Refetch and client are used', async () => { await matchTransformSnapshot('cellQueryResult', 'refetchClient') }) test('Refetch and client are used with client aliased', async () => { await matchTransformSnapshot('cellQueryResult', 'refetchClientAliased') }) test('Usage in Failure and Success', async () => { await matchTransformSnapshot('cellQueryResult', 'failureSuccess') }) })
5,134
0
petrpan-code/redwoodjs/redwood/packages/codemods/src/codemods/v5.x.x/renameValidateWith
petrpan-code/redwoodjs/redwood/packages/codemods/src/codemods/v5.x.x/renameValidateWith/__tests__/renameValidateWith.test.ts
describe('renameValidateWith', () => { it('Renames `validateWith` to `validateWithSync`', async () => { await matchTransformSnapshot('renameValidateWith', 'default') }) })
5,139
0
petrpan-code/redwoodjs/redwood/packages/codemods/src/codemods/v5.x.x/updateAuth0ToV2
petrpan-code/redwoodjs/redwood/packages/codemods/src/codemods/v5.x.x/updateAuth0ToV2/__tests__/updateAuth0ToV2.test.ts
describe('updateAuth0ToV2', () => { it('updates the web-side auth file to the v2 SDK', async () => { await matchTransformSnapshot('updateAuth0ToV2', 'default') }) })
5,148
0
petrpan-code/redwoodjs/redwood/packages/codemods/src/codemods/v5.x.x/upgradeToReact18
petrpan-code/redwoodjs/redwood/packages/codemods/src/codemods/v5.x.x/upgradeToReact18/__tests__/upgradeToReact18.test.ts
import { checkAndTransformReactRoot } from '../upgradeToReact18' describe('upgradeToReact18', () => { it('Checks and transforms the react root', async () => { await matchFolderTransform( () => checkAndTransformReactRoot({ setWarning: () => {} }), 'default' ) }) })
5,154
0
petrpan-code/redwoodjs/redwood/packages/codemods/src/codemods/v6.x.x/changeGlobalToGlobalThis
petrpan-code/redwoodjs/redwood/packages/codemods/src/codemods/v6.x.x/changeGlobalToGlobalThis/__tests__/changeGlobalToGlobalThis.test.ts
describe('changeGlobalToGlobalThis', () => { it('Converts global to globalThis', async () => { await matchTransformSnapshot('changeGlobalToGlobalThis', 'default') }) })
5,202
0
petrpan-code/redwoodjs/redwood/packages/codemods/src/codemods/v6.x.x/convertJsToJsx
petrpan-code/redwoodjs/redwood/packages/codemods/src/codemods/v6.x.x/convertJsToJsx/__tests__/convertJsToJsx.test.ts
describe('convertJsToJsx', () => { it('Converts an example project correctly', async () => { await matchFolderTransform('convertJsToJsx', 'example', { useJsCodeshift: true, targetPathsGlob: 'web/src/**/*.js', }) }) it('Converts a js file containing jsx', async () => { await matchFolderTransform('convertJsToJsx', 'withJSX', { useJsCodeshift: true, }) }) it('Ignores a js file not containing jsx', async () => { await matchFolderTransform('convertJsToJsx', 'withoutJSX', { useJsCodeshift: true, }) }) })
5,214
0
petrpan-code/redwoodjs/redwood/packages/codemods/src/codemods/v6.x.x/entryClientNullCheck
petrpan-code/redwoodjs/redwood/packages/codemods/src/codemods/v6.x.x/entryClientNullCheck/__tests__/entryClientNullCheck.test.ts
describe('entryClientNullCheck', () => { it('Handles the default case', async () => { await matchTransformSnapshot('entryClientNullCheck', 'default') }) it('User has already implemented the check', async () => { await matchTransformSnapshot('entryClientNullCheck', 'alreadyChecking') }) it('Additional code present', async () => { await matchTransformSnapshot('entryClientNullCheck', 'moreCode') }) it('Unintelligible changes to entry file', async () => { await matchTransformSnapshot('entryClientNullCheck', 'unintelligible') }) })
5,220
0
petrpan-code/redwoodjs/redwood/packages/codemods/src/codemods/v6.x.x/processEnvDotNotation
petrpan-code/redwoodjs/redwood/packages/codemods/src/codemods/v6.x.x/processEnvDotNotation/__tests__/processEnvDotNotation.test.ts
describe('processEnvDotNotation', () => { it('Replaces array access syntax with dot notation', async () => { await matchTransformSnapshot('processEnvDotNotation', 'default') }) })
5,267
0
petrpan-code/redwoodjs/redwood/packages/codemods/src/codemods/v6.x.x/replaceComponentSvgs
petrpan-code/redwoodjs/redwood/packages/codemods/src/codemods/v6.x.x/replaceComponentSvgs/__tests__/replaceComponentSvgs.test.ts
describe('replaceComponentSvgs', () => { it('Handles simple Svgs as components', async () => { await matchFolderTransform('replaceComponentSvgs', 'simple', { useJsCodeshift: true, targetPathsGlob: '**/*.{js,jsx,tsx}', removeWhitespace: true, // needed for matching }) }) it('Preserves attrs & deals with nesting', async () => { await matchFolderTransform('replaceComponentSvgs', 'complex', { useJsCodeshift: true, targetPathsGlob: '**/*.{js,jsx,tsx}', removeWhitespace: true, // needed for matching }) }) it('Deals with src alias & casing in filenames', async () => { await matchFolderTransform('replaceComponentSvgs', 'srcAlias', { useJsCodeshift: true, targetPathsGlob: '**/*.{js,jsx,tsx}', removeWhitespace: true, // needed for matching }) }) it('Deals with when SVGs are rexported', async () => { await matchFolderTransform('replaceComponentSvgs', 'reExported', { useJsCodeshift: true, targetPathsGlob: '**/*.{js,jsx,tsx}', removeWhitespace: true, // needed for matching }) }) })
5,277
0
petrpan-code/redwoodjs/redwood/packages/codemods/src/codemods/v6.x.x/updateDevFatalErrorPage
petrpan-code/redwoodjs/redwood/packages/codemods/src/codemods/v6.x.x/updateDevFatalErrorPage/__tests__/updateDevFatalErrorPage.test.ts
import { updateDevFatalErrorPage } from '../updateDevFatalErrorPage' describe('updateDevFatalErrorPage', () => { it('Replaces the js FatalErrorPage with a new version that uses a regular import', async () => { await matchFolderTransform(updateDevFatalErrorPage, 'js') }) it('Replaces the jsx FatalErrorPage with a new version that uses a regular import', async () => { await matchFolderTransform(updateDevFatalErrorPage, 'jsx') }) it('Replaces the tsx FatalErrorPage with a new version that uses a regular import', async () => { await matchFolderTransform(updateDevFatalErrorPage, 'tsx') }) })
5,285
0
petrpan-code/redwoodjs/redwood/packages/codemods/src/codemods/v6.x.x/updateThemeConfig
petrpan-code/redwoodjs/redwood/packages/codemods/src/codemods/v6.x.x/updateThemeConfig/__tests__/updateThemeConfig.test.ts
describe('updateThemeConfig', () => { it('Converts from module.exports to export default ', async () => { await matchTransformSnapshot('updateThemeConfig', 'default') }) it('Handles when config is an identifier', async () => { await matchTransformSnapshot('updateThemeConfig', 'identifierTheme') }) })
5,304
0
petrpan-code/redwoodjs/redwood/packages/codemods/tasks/generateCodemod/templates/code
petrpan-code/redwoodjs/redwood/packages/codemods/tasks/generateCodemod/templates/code/__tests__/codemod.test.ts.template
describe('${name}', () => { it('Converts world to bazinga', async () => { await matchTransformSnapshot('${name}', 'default') }) })
5,309
0
petrpan-code/redwoodjs/redwood/packages/codemods/tasks/generateCodemod/templates/structure
petrpan-code/redwoodjs/redwood/packages/codemods/tasks/generateCodemod/templates/structure/__tests__/codemod.test.ts.template
import ${name} from '../${name}' describe('${name}', () => { it('Changes the structure of a redwood project', async () => { await matchFolderTransform(${name}, 'default') }) })
5,412
0
petrpan-code/redwoodjs/redwood/packages/create-redwood-app/templates/ts/api/src/directives
petrpan-code/redwoodjs/redwood/packages/create-redwood-app/templates/ts/api/src/directives/requireAuth/requireAuth.test.ts
import { mockRedwoodDirective, getDirectiveName } from '@redwoodjs/testing/api' import requireAuth from './requireAuth' describe('requireAuth directive', () => { it('declares the directive sdl as schema, with the correct name', () => { expect(requireAuth.schema).toBeTruthy() expect(getDirectiveName(requireAuth.schema)).toBe('requireAuth') }) it('requireAuth has stub implementation. Should not throw when current user', () => { // If you want to set values in context, pass it through e.g. // mockRedwoodDirective(requireAuth, { context: { currentUser: { id: 1, name: 'Lebron McGretzky' } }}) const mockExecution = mockRedwoodDirective(requireAuth, { context: {} }) expect(mockExecution).not.toThrowError() }) })
5,414
0
petrpan-code/redwoodjs/redwood/packages/create-redwood-app/templates/ts/api/src/directives
petrpan-code/redwoodjs/redwood/packages/create-redwood-app/templates/ts/api/src/directives/skipAuth/skipAuth.test.ts
import { getDirectiveName } from '@redwoodjs/testing/api' import skipAuth from './skipAuth' describe('skipAuth directive', () => { it('declares the directive sdl as schema, with the correct name', () => { expect(skipAuth.schema).toBeTruthy() expect(getDirectiveName(skipAuth.schema)).toBe('skipAuth') }) })
5,447
0
petrpan-code/redwoodjs/redwood/packages/eslint-plugin/src
petrpan-code/redwoodjs/redwood/packages/eslint-plugin/src/__tests__/process-env-computed.test.ts
import { describe, it } from 'node:test' import { RuleTester } from 'eslint' import { processEnvComputedRule } from '../process-env-computed.js' // @ts-expect-error - Types are wrong RuleTester.describe = describe // @ts-expect-error - Types are wrong RuleTester.it = it const ruleTester = new RuleTester() ruleTester.run('process-env-computed', processEnvComputedRule, { valid: [ { code: 'process.env.foo', }, { code: 'process.env.BAR', }, { code: 'process.env.REDWOOD_ENV_FOOBAR', }, { filename: 'packages/testing/src/api/__tests__/directUrlHelpers.test.ts', code: 'expect(process.env[directUrlEnvVar]).toBe(defaultDb)', }, ], invalid: [ { code: 'process.env[foo]', errors: [ { message: 'Accessing process.env via array syntax will break in production. Use dot notation e.g. process.env.MY_ENV_VAR instead', }, ], }, { code: "process.env['BAR']", errors: [ { message: 'Accessing process.env via array syntax will break in production. Use dot notation e.g. process.env.MY_ENV_VAR instead', }, ], }, ], })
5,448
0
petrpan-code/redwoodjs/redwood/packages/eslint-plugin/src
petrpan-code/redwoodjs/redwood/packages/eslint-plugin/src/__tests__/service-type-annotations.test.ts
import { describe, it } from 'node:test' import { RuleTester } from 'eslint' import { serviceTypeAnnotations } from '../service-type-annotations.js' // @ts-expect-error - Types are wrong RuleTester.describe = describe // @ts-expect-error - Types are wrong RuleTester.it = it const ruleTester = new RuleTester({ parser: require.resolve('@typescript-eslint/parser'), }) ruleTester.run('service-type-annotations', serviceTypeAnnotations, { valid: [ { code: '// no exports', }, { code: 'function abc() {}', }, { filename: '/app/api/src/services/notificationSubscriptions/notificationSubscriptions.ts', code: ` import type { AbcResolver } from "types/notificationSubscriptions.js" export const abc: AbcResolver = () => {}`, }, ], invalid: [ { filename: '/app/api/src/services/notificationSubscriptions/notificationSubscriptions.ts', code: 'export const abc = () => {}', output: 'import type { AbcResolver } from "types/notificationSubscriptions"\n' + 'export const abc: AbcResolver = () => {}', errors: [ { message: 'The query/mutation function (abc) needs a type annotation of AbcResolver.', }, ], }, ], })
5,449
0
petrpan-code/redwoodjs/redwood/packages/eslint-plugin/src
petrpan-code/redwoodjs/redwood/packages/eslint-plugin/src/__tests__/unsupported-route-components.test.ts
import { describe, it } from 'node:test' import { ESLintUtils } from '@typescript-eslint/utils' import { unsupportedRouteComponents } from '../unsupported-route-components.js' ESLintUtils.RuleTester.describe = describe ESLintUtils.RuleTester.it = it const ruleTester = new ESLintUtils.RuleTester({ parser: '@typescript-eslint/parser', parserOptions: { ecmaVersion: 'latest', ecmaFeatures: { jsx: true, }, }, }) ruleTester.run('unsupported-route-components', unsupportedRouteComponents, { valid: [ { code: 'const Routes = () => <Router></Router>', }, { code: 'const Routes = () => <Router><Route path="/" page={HomePage} name="home" /></Router>', }, { code: 'const Routes = () => <Router><Set><Route path="/contacts" page={ContactsPage} name="contacts" /></Set></Router>', }, { code: 'const Routes = () => <Router><Private><Route path="/contacts" page={ContactsPage} name="contacts" /></Private></Router>', }, { code: ` const Routes = () => { return ( <Router> <Set> <Route path="/contacts" page={ContactsPage} name="contacts" /> </Set> </Router> ) }`.replace(/ +/g, ' '), }, ], invalid: [ { code: 'const Routes = () => <Router><div><Route path="/" page={HomePage} name="home" /></div></Router>', errors: [{ messageId: 'unexpected' }], }, { code: ` const Routes = () => { return ( <Router> <Set> <CustomElement> <Route path="/contacts" page={ContactsPage} name="contacts" /> </CustomElement> </Set> </Router> ) }`.replace(/ +/g, ' '), errors: [{ messageId: 'unexpected' }], }, ], })
5,469
0
petrpan-code/redwoodjs/redwood/packages/forms/src
petrpan-code/redwoodjs/redwood/packages/forms/src/__tests__/form.test.tsx
import React from 'react' import { toHaveFocus, toHaveClass, toBeInTheDocument, } from '@testing-library/jest-dom/matchers' import { screen, render, cleanup, fireEvent, waitFor, } from '@testing-library/react' import userEvent from '@testing-library/user-event' import { Form, TextField, NumberField, CheckboxField, TextAreaField, DatetimeLocalField, DateField, SelectField, Submit, FieldError, Label, } from '../index' expect.extend({ toHaveFocus, toHaveClass, toBeInTheDocument }) describe('Form', () => { const TestComponent = ({ onSubmit = () => {} }) => { return ( <Form onSubmit={onSubmit}> <TextField name="text" defaultValue="text" /> <NumberField name="number" defaultValue="42" /> <TextField name="floatText" defaultValue="3.14" validation={{ valueAsNumber: true }} /> <CheckboxField name="checkbox" defaultChecked={true} /> <TextAreaField name="json" defaultValue={` { "key_one": "value1", "key_two": 2, "false": false } `} validation={{ valueAsJSON: true }} /> <DatetimeLocalField name="datetimeLocal" defaultValue="2021-04-16T12:34" /> <DateField name="date" defaultValue="2021-04-16" /> <SelectField name="select1" data-testid="select1"> <option>Option 1</option> <option>Option 2</option> <option>Option 3</option> </SelectField> <SelectField name="select2" data-testid="select2" validation={{ valueAsNumber: true }} > <option value={1}>Option 1</option> <option value={2}>Option 2</option> <option value={3}>Option 3</option> </SelectField> <Submit>Save</Submit> </Form> ) } const NumberFieldsWrapper = () => ( <div> <h4>This is a wrapped form field header</h4> <div> <label htmlFor="wrapped-nf-1">Wrapped NumberField</label> <NumberField name="wrapped-nf-1" defaultValue="0101" /> </div> <div> <label htmlFor="wrapped-nf-2">Wrapped NumberField</label> <NumberField name="wrapped-nf-2" defaultValue="0102" /> </div> </div> ) const TestComponentWithWrappedFormElements = ({ onSubmit = () => {} }) => { return ( <Form onSubmit={onSubmit}> <p>Some text</p> <div className="field"> <TextField name="wrapped-ff" defaultValue="3.14" validation={{ valueAsNumber: true }} /> </div> <NumberFieldsWrapper /> <Submit>Save</Submit> </Form> ) } const TestComponentWithRef = () => { const inputEl = React.useRef<HTMLInputElement>(null) React.useEffect(() => { inputEl.current?.focus() }) return ( <Form> <TextField name="tf" defaultValue="text" ref={inputEl} /> </Form> ) } afterEach(() => { cleanup() }) it('does not crash', () => { expect(() => render(<TestComponent />)).not.toThrow() }) it('calls onSubmit', async () => { const mockFn = jest.fn() render(<TestComponent onSubmit={mockFn} />) fireEvent.click(screen.getByText('Save')) await waitFor(() => expect(mockFn).toHaveBeenCalledTimes(1)) }) it('renders and coerces user-supplied values', async () => { const mockFn = jest.fn() render(<TestComponent onSubmit={mockFn} />) await userEvent.type(screen.getByDisplayValue('text'), 'text') await userEvent.type(screen.getByDisplayValue('42'), '24') await userEvent.type(screen.getByDisplayValue('3.14'), '1592') fireEvent.change(screen.getByTestId('select1'), { target: { value: 'Option 2' }, }) fireEvent.change(screen.getByTestId('select2'), { target: { value: 3 }, }) fireEvent.click(screen.getByText('Save')) await waitFor(() => expect(mockFn).toHaveBeenCalledTimes(1)) expect(mockFn).toBeCalledWith( { text: 'texttext', number: 4224, // i.e. NOT "4224" floatText: 3.141592, select1: 'Option 2', select2: 3, checkbox: true, json: { key_one: 'value1', key_two: 2, false: false, }, datetimeLocal: new Date('2021-04-16T12:34'), date: new Date('2021-04-16'), }, expect.anything() // event that triggered the onSubmit call ) }) it('finds nested form fields to coerce', async () => { const mockFn = jest.fn() render(<TestComponentWithWrappedFormElements onSubmit={mockFn} />) fireEvent.click(screen.getByText('Save')) await waitFor(() => expect(mockFn).toHaveBeenCalledTimes(1)) expect(mockFn).toBeCalledWith( { 'wrapped-ff': 3.14, 'wrapped-nf-1': 101, 'wrapped-nf-2': 102 }, expect.anything() // event that triggered the onSubmit call ) }) it('supports ref forwarding', async () => { render(<TestComponentWithRef />) const input = screen.getByDisplayValue('text') await waitFor(() => { expect(input).toHaveFocus() }) }) it('lets users pass custom coercion functions', async () => { const mockFn = jest.fn() const coercionFunctionNumber = (value: string) => parseInt(value.replace('_', ''), 10) const coercionFunctionText = (value: string) => value.replace('_', '-') render( <Form onSubmit={mockFn}> <TextField name="tf" defaultValue="123_456" validation={{ setValueAs: coercionFunctionNumber }} /> <SelectField name="select" defaultValue="Option_2" validation={{ setValueAs: coercionFunctionText }} > <option>Option_1</option> <option>Option_2</option> </SelectField> <Submit>Save</Submit> </Form> ) fireEvent.click(screen.getByText('Save')) await waitFor(() => expect(mockFn).toHaveBeenCalledTimes(1)) expect(mockFn).toBeCalledWith( { tf: 123456, select: 'Option-2' }, expect.anything() // event that triggered the onSubmit call ) }) it('sets the value to null for empty string on relational fields', async () => { const mockFn = jest.fn() render( <Form onSubmit={mockFn}> {/* This is an optional relational field because the name ends with "Id" and it doesn't have { required: true } */} <TextField name="userId" defaultValue="" /> <SelectField name="groupId" defaultValue=""> <option value="">No group</option> <option value={1}>Group 1</option> <option value={2}>Group 2</option> </SelectField> <Submit>Save</Submit> </Form> ) fireEvent.click(screen.getByText('Save')) await waitFor(() => expect(mockFn).toHaveBeenCalledTimes(1)) expect(mockFn).toBeCalledWith( { userId: null, groupId: null }, expect.anything() // event that triggered the onSubmit call ) }) it('ensures required textField is enforced by validation', async () => { const mockFn = jest.fn() render( <Form onSubmit={mockFn}> <TextField name="userId2" defaultValue="" validation={{ required: true }} /> <FieldError name="userId2" data-testid="fieldError" /> <Submit>Save</Submit> </Form> ) fireEvent.submit(screen.getByText('Save')) await waitFor(() => expect(screen.getByTestId('fieldError')).toBeInTheDocument() ) // The validation should catch and prevent the onSubmit from being called expect(mockFn).not.toHaveBeenCalled() }) it('ensures required selectField is enforced by validation', async () => { const mockFn = jest.fn() render( <Form onSubmit={mockFn}> <SelectField name="groupId2" defaultValue="" validation={{ required: true }} > <option value="">No group</option> <option value={1}>Group 1</option> <option value={2}>Group 2</option> </SelectField> <FieldError name="groupId2" data-testid="fieldError" />{' '} <Submit>Save</Submit> </Form> ) fireEvent.submit(screen.getByText('Save')) await waitFor(() => expect(screen.getByTestId('fieldError')).toBeInTheDocument() ) // The validation should catch and prevent the onSubmit from being called expect(mockFn).not.toHaveBeenCalled() }) it('handles int and float blank values gracefully', async () => { const mockFn = jest.fn() console.log('handles int and float blank values gracefully') render( <Form onSubmit={mockFn}> <NumberField name="int" defaultValue="" /> <TextField name="float" defaultValue="" validation={{ valueAsNumber: true }} /> <Submit>Save</Submit> </Form> ) fireEvent.click(screen.getByText('Save')) await waitFor(() => expect(mockFn).toHaveBeenCalledTimes(1)) expect(mockFn).toBeCalledWith( { int: NaN, float: NaN, }, expect.anything() // event that triggered the onSubmit call ) }) // Note the good JSON case is tested in an earlier test it('does not call the onSubmit function for a bad entry into a TextAreaField with valueAsJSON', async () => { const mockFn = jest.fn() render( <Form onSubmit={mockFn}> <TextAreaField name="jsonField" defaultValue="{bad-json}" validation={{ valueAsJSON: true }} /> <FieldError name="jsonField" data-testid="fieldError" /> <Submit>Save</Submit> </Form> ) fireEvent.submit(screen.getByText('Save')) await waitFor(() => expect(screen.getByTestId('fieldError')).toBeInTheDocument() ) // The validation should catch and prevent the onSubmit from being called expect(mockFn).not.toHaveBeenCalled() }) it('displays a FieldError for a bad entry into a TextAreaField with valueAsJSON', async () => { const mockFn = jest.fn() render( <Form onSubmit={mockFn}> <TextAreaField name="jsonField" defaultValue="{bad-json}" validation={{ valueAsJSON: true }} /> <FieldError name="jsonField" data-testid="fieldError" /> <Submit>Save</Submit> </Form> ) fireEvent.submit(screen.getByText('Save')) await waitFor(() => expect(screen.getByTestId('fieldError')).toBeInTheDocument() ) // The validation should catch and prevent the onSubmit from being called expect(mockFn).not.toHaveBeenCalled() }) it('for a FieldError with name set to path', async () => { const mockFn = jest.fn() render( <Form onSubmit={mockFn}> <TextField name="phone" defaultValue="abcde" validation={{ pattern: /^[0-9]+$/i }} /> <FieldError name="phone" data-testid="phoneFieldError" /> <TextField name="address.street" data-testid="streetField" defaultValue="George123" validation={{ pattern: /^[a-zA-z]+$/i }} errorClassName="border-red" /> <FieldError name="address.street" data-testid="streetFieldError" /> <Submit>Save</Submit> </Form> ) fireEvent.submit(screen.getByText('Save')) await waitFor(() => expect(screen.getByTestId('phoneFieldError')).toBeInTheDocument() ) // The validation should catch and prevent the onSubmit from being called expect(mockFn).not.toHaveBeenCalled() const phoneError = screen.getByTestId('phoneFieldError').textContent const streetError = screen.getByTestId('streetFieldError').textContent const streetField = screen.getByTestId('streetField') expect(phoneError).toEqual('phone is not formatted correctly') expect(streetError).toEqual('address.street is not formatted correctly') expect(streetField).toHaveClass('border-red', { exact: true }) }) it("doesn't crash on Labels without name", async () => { render( <Form> {/* @ts-expect-error - pretend this is a .js file */} <Label htmlFor="phone">Input your phone number</Label> <TextField id="phone" name="phone" defaultValue="abcde" validation={{ pattern: /^[0-9]+$/i }} /> <FieldError name="phone" data-testid="phoneFieldError" /> <Submit>Save</Submit> </Form> ) fireEvent.click(screen.getByText('Save')) const phoneError = await waitFor( () => screen.getByTestId('phoneFieldError').textContent ) expect(phoneError).toEqual('phone is not formatted correctly') }) it('can handle falsy names ("false")', async () => { render( <Form> <TextField name="false" defaultValue="abcde" data-testid="phoneField" validation={{ pattern: /^[0-9]+$/i }} /> <FieldError name="false" data-testid="phoneFieldError" /> <Submit>Save</Submit> </Form> ) fireEvent.click(screen.getByText('Save')) const phoneError = await waitFor( () => screen.getByTestId('phoneFieldError').textContent ) expect(phoneError).toEqual('false is not formatted correctly') }) it('can handle falsy names ("0")', async () => { render( <Form> <TextField name="0" defaultValue="abcde" validation={{ pattern: /^[0-9]+$/i }} /> <FieldError name="0" data-testid="phoneFieldError" /> <Submit>Save</Submit> </Form> ) fireEvent.click(screen.getByText('Save')) const phoneError = await waitFor( () => screen.getByTestId('phoneFieldError').textContent ) expect(phoneError).toEqual('0 is not formatted correctly') }) it('returns appropriate values for fields with emptyAs not defined ', async () => { const mockFn = jest.fn() render( <Form onSubmit={mockFn}> <TextField name="textField" /> <TextField name="textAreaField" /> <NumberField name="numberField" /> <DateField name="dateField" /> <SelectField name="selectField" defaultValue=""> <option value="">No option selected</option> <option value={1}>Option 1</option> <option value={2}>Option 2</option> <option value={3}>Option 3</option> </SelectField> <CheckboxField name="checkboxField0" defaultChecked={false} /> <CheckboxField name="checkboxField1" defaultChecked={true} /> <TextAreaField name="jsonField" defaultValue="" validation={{ valueAsJSON: true }} /> <TextField name="fieldId" defaultValue="" /> <Submit>Save</Submit> </Form> ) fireEvent.click(screen.getByText('Save')) await waitFor(() => expect(mockFn).toHaveBeenCalledTimes(1)) expect(mockFn).toBeCalledWith( { textField: '', textAreaField: '', numberField: NaN, dateField: null, selectField: '', checkboxField0: false, checkboxField1: true, jsonField: null, fieldId: null, }, expect.anything() // event that triggered the onSubmit call ) }) it(`returns appropriate values for non-empty fields with emptyAs={'undefined'}`, async () => { const mockFn = jest.fn() render( <Form onSubmit={mockFn}> <TextField name="textField" emptyAs={'undefined'} /> <TextAreaField name="textAreaField" emptyAs={'undefined'} /> <NumberField name="numberField" emptyAs={'undefined'} /> <DateField name="dateField" emptyAs={'undefined'} /> <SelectField name="selectField" defaultValue="" emptyAs={'undefined'}> <option value="">No option selected</option> <option value={1}>Option 1</option> <option value={2}>Option 2</option> <option value={3}>Option 3</option> </SelectField> <SelectField name="selectFieldAsNumber" defaultValue="" emptyAs={'undefined'} validation={{ valueAsNumber: true }} > <option value={''}>No option selected</option> <option value={1}>Option 1</option> <option value={2}>Option 2</option> <option value={3}>Option 3</option> </SelectField> <TextAreaField name="jsonField" defaultValue="" validation={{ valueAsJSON: true }} emptyAs={'undefined'} /> <TextField name="fieldId" defaultValue="" emptyAs={'undefined'} /> <Submit>Save</Submit> </Form> ) fireEvent.click(screen.getByText('Save')) await waitFor(() => expect(mockFn).toHaveBeenCalledTimes(1)) expect(mockFn).toBeCalledWith( { textField: undefined, textAreaField: undefined, numberField: undefined, dateField: undefined, selectField: undefined, selectFieldAsNumber: undefined, jsonField: undefined, fieldId: undefined, }, expect.anything() // event that triggered the onSubmit call ) }) it('returns null for empty fields with emptyAs={null}', async () => { const mockFn = jest.fn() render( <Form onSubmit={mockFn}> <TextField name="textField" emptyAs={null} /> <TextAreaField name="textAreaField" emptyAs={null} /> <NumberField name="numberField" emptyAs={null} /> <DateField name="dateField" emptyAs={null} /> <SelectField name="selectField" defaultValue="" emptyAs={null}> <option value="">No option selected</option> <option value={1}>Option 1</option> <option value={2}>Option 2</option> <option value={3}>Option 3</option> </SelectField> <TextAreaField name="jsonField" defaultValue="" validation={{ valueAsJSON: true }} emptyAs={null} /> <TextField name="fieldId" defaultValue="" emptyAs={null} /> <Submit>Save</Submit> </Form> ) fireEvent.click(screen.getByText('Save')) await waitFor(() => expect(mockFn).toHaveBeenCalledTimes(1)) expect(mockFn).toBeCalledWith( { textField: null, textAreaField: null, numberField: null, dateField: null, selectField: null, jsonField: null, fieldId: null, }, expect.anything() // event that triggered the onSubmit call ) }) it('returns appropriate value empty fields with emptyAs={0}', async () => { const mockFn = jest.fn() render( <Form onSubmit={mockFn}> <TextField name="textField" emptyAs={0} /> <TextAreaField name="textAreaField" emptyAs={0} /> <NumberField name="numberField" emptyAs={0} /> <DateField name="dateField" emptyAs={0} /> <SelectField name="selectField" defaultValue="" emptyAs={0}> <option value="">No option selected</option> <option value={1}>Option 1</option> <option value={2}>Option 2</option> <option value={3}>Option 3</option> </SelectField> <TextAreaField name="jsonField" defaultValue="" validation={{ valueAsJSON: true }} emptyAs={0} /> <TextField name="fieldId" defaultValue="" emptyAs={0} /> <Submit>Save</Submit> </Form> ) fireEvent.click(screen.getByText('Save')) await waitFor(() => expect(mockFn).toHaveBeenCalledTimes(1)) expect(mockFn).toBeCalledWith( { textField: 0, textAreaField: 0, numberField: 0, dateField: 0, selectField: 0, jsonField: 0, fieldId: 0, }, expect.anything() // event that triggered the onSubmit call ) }) it(`returns an empty string empty fields with emptyAs={''}`, async () => { const mockFn = jest.fn() render( <Form onSubmit={mockFn}> <TextField name="textField" emptyAs={''} /> <TextAreaField name="textAreaField" emptyAs={''} /> <NumberField name="numberField" emptyAs={''} /> <DateField name="dateField" emptyAs={''} /> <SelectField name="selectField" defaultValue="" emptyAs={''}> <option value="">No option selected</option> <option value={1}>Option 1</option> <option value={2}>Option 2</option> <option value={3}>Option 3</option> </SelectField> <TextAreaField name="jsonField" defaultValue="" validation={{ valueAsJSON: true }} emptyAs={''} /> <TextField name="fieldId" defaultValue="" emptyAs={''} /> <Submit>Save</Submit> </Form> ) fireEvent.click(screen.getByText('Save')) await waitFor(() => expect(mockFn).toHaveBeenCalledTimes(1)) expect(mockFn).toBeCalledWith( { textField: '', textAreaField: '', numberField: '', dateField: '', selectField: '', jsonField: '', fieldId: '', }, expect.anything() // event that triggered the onSubmit call ) }) it('should have appropriate validation for NumberFields and DateFields with emptyAs={null}', async () => { const mockFn = jest.fn() render( <Form onSubmit={mockFn}> <NumberField name="numberField" data-testid="numberField" emptyAs={null} validation={{ min: 10 }} /> <FieldError name="numberField" data-testid="numberFieldError" /> <DateField name="dateField" emptyAs={null} /> <Submit>Save</Submit> </Form> ) fireEvent.change(screen.getByTestId('numberField'), { target: { value: 2 }, }) fireEvent.submit(screen.getByText('Save')) await waitFor(() => expect(screen.getByTestId('numberFieldError')).toBeInTheDocument() ) // The validation should catch and prevent the onSubmit from being called expect(mockFn).not.toHaveBeenCalled() }) it(`handles invalid emptyAs values with default values`, async () => { const mockFn = jest.fn() render( <Form onSubmit={mockFn}> {/* @ts-expect-error - pretend this is a .js file */} <TextField name="textField" emptyAs={'badEmptyAsValue'} /> {/* @ts-expect-error - pretend this is a .js file */} <TextAreaField name="textAreaField" emptyAs={'badEmptyAsValue'} /> {/* @ts-expect-error - pretend this is a .js file */} <NumberField name="numberField" emptyAs={'badEmptyAsValue'} /> {/* @ts-expect-error - pretend this is a .js file */} <DateField name="dateField" emptyAs={'badEmptyAsValue'} /> <SelectField name="selectField" defaultValue="" /* @ts-expect-error - pretend this is a .js file */ emptyAs={'badEmptyAsValue'} > <option value="">No option selected</option> <option value={1}>Option 1</option> <option value={2}>Option 2</option> <option value={3}>Option 3</option> </SelectField> <TextAreaField name="jsonField" defaultValue="" validation={{ valueAsJSON: true }} /* @ts-expect-error - pretend this is a .js file */ emptyAs={'badEmptyAsValue'} /> {/* @ts-expect-error - pretend this is a .js file */} <TextField name="fieldId" defaultValue="" emptyAs={'badEmptyAsValue'} /> <Submit>Save</Submit> </Form> ) fireEvent.click(screen.getByText('Save')) await waitFor(() => expect(mockFn).toHaveBeenCalledTimes(1)) expect(mockFn).toBeCalledWith( { textField: '', textAreaField: '', numberField: NaN, dateField: null, selectField: '', jsonField: null, fieldId: null, }, expect.anything() // event that triggered the onSubmit call ) }) it('should return a number for a textfield with valueAsNumber, regardless of emptyAs', async () => { const mockFn = jest.fn() render( <Form onSubmit={mockFn}> <TextField name="tf1" validation={{ valueAsNumber: true }} defaultValue="42" /> <TextField name="tf2" validation={{ valueAsNumber: true }} defaultValue="42" emptyAs={'undefined'} /> <TextField name="tf3" validation={{ valueAsNumber: true }} defaultValue="42" emptyAs={null} /> <TextField name="tf4" validation={{ valueAsNumber: true }} defaultValue="42" emptyAs={0} /> <Submit>Save</Submit> </Form> ) fireEvent.click(screen.getByText('Save')) await waitFor(() => expect(mockFn).toHaveBeenCalledTimes(1)) expect(mockFn).toBeCalledWith( { tf1: 42, tf2: 42, tf3: 42, tf4: 42, }, expect.anything() // event that triggered the onSubmit call ) }) it('should return a date for a textfield with valueAsDate, regardless of emptyAs', async () => { const mockFn = jest.fn() render( <Form onSubmit={mockFn}> <TextField name="tf1" validation={{ valueAsDate: true }} defaultValue="2022-02-01" /> <TextField name="tf2" validation={{ valueAsDate: true }} defaultValue="2022-02-01" emptyAs={'undefined'} /> <TextField name="tf3" validation={{ valueAsDate: true }} defaultValue="2022-02-01" emptyAs={null} /> <TextField name="tf4" validation={{ valueAsDate: true }} defaultValue="2022-02-01" emptyAs={0} /> <Submit>Save</Submit> </Form> ) fireEvent.click(screen.getByText('Save')) await waitFor(() => expect(mockFn).toHaveBeenCalledTimes(1)) expect(mockFn).toBeCalledWith( { tf1: new Date('2022-02-01'), tf2: new Date('2022-02-01'), tf3: new Date('2022-02-01'), tf4: new Date('2022-02-01'), }, expect.anything() // event that triggered the onSubmit call ) }) it('should throw an intelligible error if the name prop is missing', async () => { const mockFn = jest.fn() const testRender = () => render( <Form onSubmit={mockFn}> {/* @ts-expect-error - Testing a JS scenario */} <TextField /> <Submit>Save</Submit> </Form> ) expect(testRender).toThrow('`name` prop must be provided') }) })
5,490
0
petrpan-code/redwoodjs/redwood/packages/graphql-server/src
petrpan-code/redwoodjs/redwood/packages/graphql-server/src/__tests__/cors.test.ts
import type { APIGatewayProxyEvent, Context } from 'aws-lambda' import { createLogger } from '@redwoodjs/api/logger' import { createGraphQLHandler } from '../functions/graphql' jest.mock('../makeMergedSchema', () => { const { makeExecutableSchema } = require('@graphql-tools/schema') // Return executable schema return { makeMergedSchema: () => makeExecutableSchema({ typeDefs: /* GraphQL */ ` type Query { me: User! } type Query { forbiddenUser: User! getUser(id: Int!): User! } type User { id: ID! name: String! } `, resolvers: { Query: { me: () => { return { _id: 1, firstName: 'Ba', lastName: 'Zinga' } }, forbiddenUser: () => { throw Error('You are forbidden') }, getUser: (id) => { return { id, firstName: 'Ba', lastName: 'Zinga' } }, }, User: { id: (u) => u._id, name: (u) => `${u.firstName} ${u.lastName}`, }, }, }), } }) jest.mock('../directives/makeDirectives', () => { return { makeDirectivesForPlugin: () => [], } }) interface MockLambdaParams { headers?: { [key: string]: string } body?: string | null httpMethod: string [key: string]: any } const mockLambdaEvent = ({ headers, body = null, httpMethod, ...others }: MockLambdaParams): APIGatewayProxyEvent => { return { headers: headers || {}, body, httpMethod, multiValueQueryStringParameters: null, isBase64Encoded: false, multiValueHeaders: {}, // this is silly - the types require a value. It definitely can be undefined, e.g. on Vercel. path: '/graphql', pathParameters: null, stageVariables: null, queryStringParameters: null, requestContext: null as any, resource: null as any, ...others, } } describe('CORS', () => { it('Returns the origin correctly when configured in handler', async () => { const handler = createGraphQLHandler({ loggerConfig: { logger: createLogger({}), options: {} }, sdls: {}, directives: {}, services: {}, cors: { origin: 'https://web.redwoodjs.com', }, onException: () => {}, }) const mockedEvent = mockLambdaEvent({ headers: { origin: 'https://redwoodjs.com', 'Content-Type': 'application/json', }, body: JSON.stringify({ query: '{ me { id, name } }' }), httpMethod: 'POST', }) const response = await handler(mockedEvent, {} as Context) expect(response.statusCode).toBe(200) expect(response.headers['access-control-allow-origin']).toEqual( 'https://web.redwoodjs.com' ) }) it('Returns requestOrigin if cors origin set to true', async () => { const handler = createGraphQLHandler({ loggerConfig: { logger: createLogger({}), options: {} }, sdls: {}, directives: {}, services: {}, cors: { origin: true, }, onException: () => {}, }) const mockedEvent = mockLambdaEvent({ headers: { origin: 'https://someothersite.newjsframework.com', 'Content-Type': 'application/json', }, body: JSON.stringify({ query: '{ me { id, name } }' }), httpMethod: 'POST', }) const response = await handler(mockedEvent, {} as Context) expect(response.statusCode).toBe(200) expect(response.headers['access-control-allow-origin']).toEqual( 'https://someothersite.newjsframework.com' ) }) it('Returns the origin for OPTIONS requests', async () => { const handler = createGraphQLHandler({ loggerConfig: { logger: createLogger({}), options: {} }, sdls: {}, directives: {}, services: {}, cors: { origin: 'https://mycrossdomainsite.co.uk', }, onException: () => {}, }) const mockedEvent = mockLambdaEvent({ headers: { origin: 'https://someothersite.newjsframework.com', 'Content-Type': 'application/json', }, httpMethod: 'OPTIONS', }) const response = await handler(mockedEvent, {} as Context) expect(response.statusCode).toBe(204) expect(response.headers['access-control-allow-origin']).toEqual( 'https://mycrossdomainsite.co.uk' ) }) it('Does not return cross origin headers if option not specified', async () => { const handler = createGraphQLHandler({ loggerConfig: { logger: createLogger({}), options: {} }, sdls: {}, directives: {}, services: {}, onException: () => {}, }) const mockedEvent = mockLambdaEvent({ headers: { origin: 'https://someothersite.newjsframework.com', 'Content-Type': 'application/json', }, httpMethod: 'OPTIONS', }) const response = await handler(mockedEvent, {} as Context) expect(response.statusCode).toBe(204) const resHeaderKeys = Object.keys(response.headers) expect(resHeaderKeys).not.toContain('access-control-allow-origin') expect(resHeaderKeys).not.toContain('access-control-allow-credentials') }) it('Returns the requestOrigin when more than one origin supplied in config', async () => { const handler = createGraphQLHandler({ loggerConfig: { logger: createLogger({}), options: {} }, sdls: {}, directives: {}, services: {}, cors: { origin: ['https://site1.one', 'https://site2.two'], }, onException: () => {}, }) const mockedEvent: APIGatewayProxyEvent = mockLambdaEvent({ headers: { origin: 'https://site2.two', 'Content-Type': 'application/json', }, body: JSON.stringify({ query: '{ me { id, name } }' }), httpMethod: 'POST', }) const response = await handler(mockedEvent, {} as Context) expect(response.statusCode).toBe(200) // Note: no multiValueHeaders in request, so we expect response to be in headers too expect(response.headers['access-control-allow-origin']).toEqual( 'https://site2.two' ) }) it('Returns CORS headers with multiValueHeaders in request, as MVH in response', async () => { const handler = createGraphQLHandler({ loggerConfig: { logger: createLogger({}), options: {} }, sdls: {}, directives: {}, services: {}, cors: { origin: ['https://site1.one', 'https://site2.two'], }, onException: () => {}, }) const mockedEvent: APIGatewayProxyEvent = mockLambdaEvent({ headers: { origin: 'https://site2.two', 'Content-Type': 'application/json', }, body: JSON.stringify({ query: '{ me { id, name } }' }), multiValueHeaders: { origin: ['https://site2.two'], 'Content-Type': ['application/json'], }, httpMethod: 'POST', }) const response = await handler(mockedEvent, {} as Context) expect(response.statusCode).toBe(200) expect(response.headers['access-control-allow-origin']).toEqual( 'https://site2.two' ) }) })
5,491
0
petrpan-code/redwoodjs/redwood/packages/graphql-server/src
petrpan-code/redwoodjs/redwood/packages/graphql-server/src/__tests__/graphiql.test.ts
import { configureGraphiQLPlayground } from '../graphiql' describe('configureGraphiQLPlayground', () => { describe('when not in development environment', () => { const curNodeEnv = process.env.NODE_ENV beforeAll(() => { process.env.NODE_ENV = 'not-development' }) afterAll(() => { process.env.NODE_ENV = curNodeEnv expect(process.env.NODE_ENV).toBe('test') }) it('should return false when no config is provided', () => { const result = configureGraphiQLPlayground({}) expect(result).toBe(false) }) it('should configure the GraphiQL Playground when allowGraphiQL is true', () => { const result = configureGraphiQLPlayground({ allowGraphiQL: true, generateGraphiQLHeader: jest.fn(), }) expect(result).not.toBe(false) expect(result).toMatchSnapshot() }) it('should return false when allowGraphiQL is false', () => { const result = configureGraphiQLPlayground({ allowGraphiQL: false, generateGraphiQLHeader: jest.fn(), }) expect(result).toBe(false) }) it('should return false when allowGraphiQL is not provided', () => { const result = configureGraphiQLPlayground({ generateGraphiQLHeader: jest.fn(), }) expect(result).toBe(false) }) it('should return false when allowGraphiQL is undefined', () => { const result = configureGraphiQLPlayground({ allowGraphiQL: undefined, generateGraphiQLHeader: jest.fn(), }) expect(result).toBe(false) }) it('should return false when allowGraphiQL is null', () => { const result = configureGraphiQLPlayground({ // @ts-expect-error - We don't explicitly allow null, but we will cover it in the tests anyway allowGraphiQL: null, generateGraphiQLHeader: jest.fn(), }) expect(result).toBe(false) }) }) describe('when in development', () => { const curNodeEnv = process.env.NODE_ENV beforeAll(() => { process.env.NODE_ENV = 'development' }) afterAll(() => { process.env.NODE_ENV = curNodeEnv expect(process.env.NODE_ENV).toBe('test') }) it('should configure the GraphiQL Playground when no config is provided', () => { const result = configureGraphiQLPlayground({}) expect(result).not.toBe(false) expect(result).toMatchSnapshot() }) it('should configure the GraphiQL Playground when allowGraphiQL is true', () => { const result = configureGraphiQLPlayground({ allowGraphiQL: true, generateGraphiQLHeader: jest.fn(), }) expect(result).not.toBe(false) expect(result).toMatchSnapshot() }) it('should configure the GraphiQL Playground when allowGraphiQL is false', () => { const result = configureGraphiQLPlayground({ allowGraphiQL: false, generateGraphiQLHeader: jest.fn(), }) expect(result).toBe(false) }) it('should configure the GraphiQL Playground when allowGraphiQL is not provided', () => { const result = configureGraphiQLPlayground({ generateGraphiQLHeader: jest.fn(), }) expect(result).not.toBe(false) expect(result).toMatchSnapshot() }) it('should configure the GraphiQL Playground when allowGraphiQL is undefined', () => { const result = configureGraphiQLPlayground({ allowGraphiQL: undefined, generateGraphiQLHeader: jest.fn(), }) expect(result).not.toBe(false) expect(result).toMatchSnapshot() }) it('should configure the GraphiQL Playground when allowGraphiQL is null', () => { const result = configureGraphiQLPlayground({ // @ts-expect-error - We don't explicitly allow null, but we will cover it in the tests anyway allowGraphiQL: null, generateGraphiQLHeader: jest.fn(), }) expect(result).not.toBe(false) expect(result).toMatchSnapshot() }) }) })
5,492
0
petrpan-code/redwoodjs/redwood/packages/graphql-server/src
petrpan-code/redwoodjs/redwood/packages/graphql-server/src/__tests__/introspection.test.ts
import { configureGraphQLIntrospection } from '../introspection' describe('configureGraphQLIntrospection', () => { describe('when not in development environment', () => { const curNodeEnv = process.env.NODE_ENV beforeAll(() => { process.env.NODE_ENV = 'not-development' }) afterAll(() => { process.env.NODE_ENV = curNodeEnv expect(process.env.NODE_ENV).toBe('test') }) it('should not disable GraphQL Introspection when allowIntrospection is true', () => { const { disableIntrospection } = configureGraphQLIntrospection({ allowIntrospection: true, }) expect(disableIntrospection).toBe(false) }) it('should disable GraphQL Introspection when allowIntrospection is false', () => { const { disableIntrospection } = configureGraphQLIntrospection({ allowIntrospection: false, }) expect(disableIntrospection).toBe(true) }) it('should disable GraphQL Introspection when allowIntrospection is not provided', () => { const { disableIntrospection } = configureGraphQLIntrospection({}) expect(disableIntrospection).toBe(true) }) it('should disable GraphQL Introspection when allowIntrospection is undefined', () => { const { disableIntrospection } = configureGraphQLIntrospection({ allowIntrospection: undefined, }) expect(disableIntrospection).toBe(true) }) it('should disable GraphQL Introspection when allowIntrospection is null', () => { const { disableIntrospection } = configureGraphQLIntrospection({ // @ts-expect-error - We don't explicitly allow null, but we will cover it in the tests anyway allowIntrospection: null, }) expect(disableIntrospection).toBe(true) }) }) describe('when in development', () => { const curNodeEnv = process.env.NODE_ENV beforeAll(() => { process.env.NODE_ENV = 'development' }) afterAll(() => { process.env.NODE_ENV = curNodeEnv expect(process.env.NODE_ENV).toBe('test') }) it('should not disable GraphQL Introspection when allowIntrospection is true', () => { const { disableIntrospection } = configureGraphQLIntrospection({ allowIntrospection: true, }) expect(disableIntrospection).toBe(false) }) it('should disable GraphQL Introspection when allowIntrospection is false', () => { const { disableIntrospection } = configureGraphQLIntrospection({ allowIntrospection: false, }) expect(disableIntrospection).toBe(true) }) it('should not disable GraphQL Introspection when allowIntrospection is not provided', () => { const { disableIntrospection } = configureGraphQLIntrospection({}) expect(disableIntrospection).toBe(false) }) it('should not disable GraphQL Introspection when allowIntrospection is undefined', () => { const { disableIntrospection } = configureGraphQLIntrospection({ allowIntrospection: undefined, }) expect(disableIntrospection).toBe(false) }) it('should not disable GraphQL Introspection when allowIntrospection is null', () => { const { disableIntrospection } = configureGraphQLIntrospection({ // @ts-expect-error - We don't explicitly allow null, but we will cover it in the tests anyway allowIntrospection: null, }) expect(disableIntrospection).toBe(false) }) }) })
5,493
0
petrpan-code/redwoodjs/redwood/packages/graphql-server/src
petrpan-code/redwoodjs/redwood/packages/graphql-server/src/__tests__/makeDirectives.test.ts
import gql from 'graphql-tag' import type { DirectiveParams } from '..' import { makeDirectivesForPlugin, createTransformerDirective, createValidatorDirective, } from '../directives/makeDirectives' const fooSchema = gql` directive @foo on FIELD_DEFINITION ` const bazingaSchema = gql` directive @bazinga on FIELD_DEFINITION ` const barSchema = gql` directive @bar on FIELD_DEFINITION ` test('Should map directives globs to defined structure correctly', async () => { // Mocking what our import-dir plugin would do const directiveFiles = { foo_directive: { schema: fooSchema, foo: createTransformerDirective(fooSchema, () => 'I am foo'), }, nested_bazinga_directive: { bazinga: createValidatorDirective(bazingaSchema, async () => { throw new Error('Only soft kittens allowed') }), schema: bazingaSchema, }, heavily_nested_bar_directive: { bar: createTransformerDirective(barSchema, () => 'I am bar'), schema: barSchema, }, } const [fooDirective, bazingaDirective, barDirective] = makeDirectivesForPlugin(directiveFiles) expect(fooDirective.name).toBe('foo') expect(fooDirective.onResolvedValue({} as DirectiveParams)).toBe('I am foo') expect(fooDirective.schema.kind).toBe('Document') expect(bazingaDirective.name).toBe('bazinga') expect(bazingaDirective.onResolvedValue).rejects.toThrowError( 'Only soft kittens allowed' ) expect(bazingaDirective.schema.kind).toBe('Document') expect(barDirective.name).toBe('bar') expect(await barDirective.onResolvedValue({} as DirectiveParams)).toBe( 'I am bar' ) expect(barDirective.schema.kind).toBe('Document') }) describe('Errors out with a helpful message, if the directive is not constructed correctly', () => { it('Tells you if you forgot to wrap the implementation function', () => { const incorrectDirectiveFiles = { foo_directive: { schema: fooSchema, foo: () => 'Oopy I forgot to wrap', }, } expect(() => makeDirectivesForPlugin(incorrectDirectiveFiles)).toThrowError( 'Please use `createValidatorDirective` or `createTransformerDirective` functions to define your directive' ) }) it('Tells you if you forgot the implementation function', () => { expect(() => createValidatorDirective(fooSchema, undefined)).toThrowError( 'Directive validation function not implemented for @foo' ) expect(() => createTransformerDirective(fooSchema, undefined)).toThrowError( 'Directive transformer function not implemented for @foo' ) }) it('Tells you if you messed up the schema', () => { // The messages come from the graphql libs, so no need to check the messages expect(() => createValidatorDirective(gql`directive @misdirective`, undefined) ).toThrow() expect(() => createTransformerDirective(gql`misdirective`, undefined) ).toThrow() }) })
5,494
0
petrpan-code/redwoodjs/redwood/packages/graphql-server/src
petrpan-code/redwoodjs/redwood/packages/graphql-server/src/__tests__/makeMergedSchema.test.ts
import type { GraphQLResolveInfo } from 'graphql' import { parse, graphql, GraphQLError } from 'graphql' import gql from 'graphql-tag' import { makeDirectivesForPlugin, createTransformerDirective, createValidatorDirective, } from '../directives/makeDirectives' import { makeMergedSchema } from '../makeMergedSchema' import type { GraphQLTypeWithFields, ServicesGlobImports, SdlGlobImports, } from '../types' jest.mock('@redwoodjs/project-config', () => { return { getConfig: () => { return { experimental: { opentelemetry: { enabled: false, }, }, } }, } }) describe('makeMergedSchema', () => { // Simulate `importAll` // ./graphql/tests.sdl.js const sdls = { tests: { schema: parse(` type MyOwnType { inTypeResolverAndServices: String inTypeResolver: String inTypeServices: String } type MySecondType { name: String inTypeResolver: String } type MyDuplicateType { name: String inTypeResolver: String } union MyUnionType = MyOwnType | MySecondType union MyUnionTypeWithSameFields = MySecondType | MyDuplicateType type Query { myOwnType: MyOwnType @foo searchType: MyUnionType @foo searchTypeSameFields: MyUnionTypeWithSameFields @foo searchTypeSameFieldsWithTypename: MyUnionTypeWithSameFields @foo inResolverAndServices: String @foo inResolver: String @foo inServices: String @foo foo: String @foo } `), resolvers: { MyOwnType: { inTypeResolverAndServices: () => "MyOwnType: I'm defined in the resolver.", inTypeResolver: () => "MyOwnType: I'm defined in the resolver.", }, MySecondType: { inTypeResolver: () => "MySecondType: I'm defined in the resolver.", }, Query: { inResolverAndServices: () => "I'm defined in the resolver.", inResolver: () => "I'm defined in the resolver.", foo: () => "I'm using @foo directive", searchType: () => ({ name: 'MySecondType', inTypeResolver: "MySecondType: I'm defined in the resolver.", }), searchTypeSameFields: () => ({ name: 'MySecondType', inTypeResolver: "MySecondType: I'm defined in the resolver.", }), searchTypeSameFieldsWithTypename: () => ({ __typename: 'MySecondType', name: 'MySecondType', inTypeResolver: "MySecondType: I'm defined in the resolver.", }), }, }, }, } as unknown as SdlGlobImports // ./services/tests.js const services = { tests: { MyOwnType: { inTypeServices: () => "MyOwnType: I'm defined in the services.", }, inResolverAndServices: () => 'I should NOT be called.', inServices: () => "I'm defined in the service.", }, } as unknown as ServicesGlobImports // mimics the directives glob file structure const fooSchema = gql` directive @foo on FIELD_DEFINITION ` const bazingaSchema = gql` directive @bazinga on FIELD_DEFINITION ` const barSchema = gql` directive @bar on FIELD_DEFINITION ` const directiveFiles = { foo_directive: { schema: fooSchema, foo: createTransformerDirective(fooSchema, () => 'I am foo'), }, nested_bazinga_directive: { bazinga: createValidatorDirective(bazingaSchema, async () => { throw new Error('Only soft kittens allowed') }), schema: bazingaSchema, }, heavily_nested_bar_directive: { bar: createTransformerDirective(barSchema, () => 'I am bar'), schema: barSchema, }, } const schema = makeMergedSchema({ sdls, services, subscriptions: [], directives: makeDirectivesForPlugin(directiveFiles), }) describe('Query Type', () => { const queryType = schema.getType('Query') as GraphQLTypeWithFields const queryFields = queryType.getFields() it('Resolver functions are mapped correctly.', () => { expect( queryFields.inResolver.resolve && queryFields.inResolver.resolve( null, {}, null, {} as GraphQLResolveInfo ) ).toEqual("I'm defined in the resolver.") }) it('Resolver functions take preference over service functions.', () => { expect( queryFields.inResolverAndServices.resolve && queryFields.inResolverAndServices.resolve( null, {}, null, {} as GraphQLResolveInfo ) ).toEqual("I'm defined in the resolver.") }) it('Service functions are mapped correctly.', async () => { expect( queryFields.inServices.resolve && (await queryFields.inServices.resolve( null, {}, null, {} as GraphQLResolveInfo )) ).toEqual("I'm defined in the service.") }) }) describe('MyOwnType', () => { const myOwnType = schema.getType('MyOwnType') as GraphQLTypeWithFields const myOwnTypeFields = myOwnType.getFields() it('Resolver functions are mapped correctly', () => { expect( myOwnTypeFields.inTypeResolverAndServices.resolve && myOwnTypeFields.inTypeResolverAndServices.resolve( null, {}, null, {} as GraphQLResolveInfo ) ).toEqual("MyOwnType: I'm defined in the resolver.") }) it('Resolver functions take preference over service functions.', () => { expect( myOwnTypeFields.inTypeResolver.resolve && myOwnTypeFields.inTypeResolver.resolve( null, {}, null, {} as GraphQLResolveInfo ) ).toEqual("MyOwnType: I'm defined in the resolver.") }) it('Service functions are mapped correctly.', async () => { expect( myOwnTypeFields.inTypeServices.resolve && (await myOwnTypeFields.inTypeServices.resolve( null, {}, null, {} as GraphQLResolveInfo )) ).toEqual("MyOwnType: I'm defined in the services.") }) }) describe('MyUnionType', () => { it('supports querying a union and having __resolveType correctly created to decide what member it is', async () => { const query = `query { searchType { ... on MySecondType { name } } }` const res = await graphql({ schema, source: query }) expect(res.errors).toBeUndefined() expect((res.data as any).searchType.name).toBe('MySecondType') }) }) describe('MyUnionTypeSameFields', () => { it('throws an error if union types have same fields and resolver cannot resolve the correct type', async () => { const query = `query { searchTypeSameFields { ... on MySecondType { name } } }` const res = await graphql({ schema, source: query }) expect(res.errors).toEqual([ new GraphQLError( 'Unable to resolve correct type for union. Try adding unique fields to each type or __typename to each resolver' ), ]) expect((res.data as any).searchTypeSameFields).toBeNull() }) }) describe('MyUnionTypeWithTypename', () => { it('supports querying a union and having __resolveType correctly created to decide what member it is', async () => { const query = `query { searchTypeSameFieldsWithTypename { ... on MySecondType { name } } }` const res = await graphql({ schema, source: query }) expect(res.errors).toBeUndefined() expect((res.data as any).searchTypeSameFieldsWithTypename.name).toBe( 'MySecondType' ) }) }) describe('Directives', () => { it('Confirms that directives have been made from a set of files and added to schema.', () => { expect(schema.getDirective('foo')).toBeTruthy() expect(schema.getDirective('bazinga')).toBeTruthy() expect(schema.getDirective('bar')).toBeTruthy() }) it('Checks that an unknown directive does not get added to the schema.', () => { expect(schema.getDirective('misdirective')).toBeFalsy() }) }) })
5,495
0
petrpan-code/redwoodjs/redwood/packages/graphql-server/src
petrpan-code/redwoodjs/redwood/packages/graphql-server/src/__tests__/makeSubscriptions.test.ts
import gql from 'graphql-tag' import { makeSubscriptions } from '../subscriptions/makeSubscriptions' const countdownSchema = gql` type Subscription { countdown(from: Int!, interval: Int!): Int! } ` const newMessageSchema = gql` type Message { from: String body: String } type Subscription { newMessage(roomId: ID!): Message! } ` describe('Should map subscription globs to defined structure correctly', () => { it('Should map a subscribe correctly', async () => { // Mocking what our import-dir plugin would do const subscriptionFiles = { countdown_subscription: { schema: countdownSchema, countdown: { async *subscribe(_, { from, interval }) { for (let i = from; i >= 0; i--) { await new Promise((resolve) => setTimeout(resolve, interval ?? 1000) ) yield { countdown: i } } }, }, }, } const [countdownSubscription] = makeSubscriptions(subscriptionFiles) expect(countdownSubscription.schema.kind).toBe('Document') expect(countdownSubscription.name).toBe('countdown') expect(countdownSubscription.resolvers.subscribe).toBeDefined() expect(countdownSubscription.resolvers.resolve).not.toBeDefined() }) it('Should map a subscribe and resolve correctly', async () => { // Mocking what our import-dir plugin would do const subscriptionFiles = { newMessage_subscription: { schema: newMessageSchema, newMessage: { subscribe: (_, { roomId }) => { return roomId }, resolve: (payload) => { return payload }, }, }, } const [newMessageSubscription] = makeSubscriptions(subscriptionFiles) expect(newMessageSubscription.schema.kind).toBe('Document') expect(newMessageSubscription.name).toBe('newMessage') expect(newMessageSubscription.resolvers.subscribe).toBeDefined() expect(newMessageSubscription.resolvers.resolve).toBeDefined() }) })
5,496
0
petrpan-code/redwoodjs/redwood/packages/graphql-server/src
petrpan-code/redwoodjs/redwood/packages/graphql-server/src/__tests__/mapRwCorsToYoga.test.ts
import { mapRwCorsOptionsToYoga } from '../cors' /** Yoga CORS Options looks like * * export interface CORSOptions { origin?: string[]; methods?: string[]; allowedHeaders?: string[]; exposedHeaders?: string[]; credentials?: boolean; maxAge?: number; } * */ describe('mapRwCorsOptionsToYoga', () => { it('Handles single endpoint, headers and method', () => { const output = mapRwCorsOptionsToYoga({ origin: 'http://localhost:8910', allowedHeaders: 'X-Bazinga', methods: 'PATCH', credentials: true, }) expect(output).toEqual({ credentials: true, allowedHeaders: ['X-Bazinga'], methods: ['PATCH'], origin: ['http://localhost:8910'], }) }) it('Handles options as an array', () => { const output = mapRwCorsOptionsToYoga({ origin: ['http://localhost:8910'], credentials: false, allowedHeaders: ['X-Bazinga', 'X-Kittens', 'Authorization'], methods: ['PATCH', 'PUT', 'POST'], }) expect(output).toEqual({ origin: ['http://localhost:8910'], methods: ['PATCH', 'PUT', 'POST'], allowedHeaders: ['X-Bazinga', 'X-Kittens', 'Authorization'], }) }) it('Handles multiple endpoints', () => { const output = mapRwCorsOptionsToYoga({ origin: ['https://bazinga.com', 'https://softkitty.mew'], credentials: true, allowedHeaders: ['X-Bazinga', 'X-Kittens', 'Authorization'], methods: ['PATCH', 'PUT', 'POST'], }) expect(output).toEqual({ credentials: true, origin: ['https://bazinga.com', 'https://softkitty.mew'], methods: ['PATCH', 'PUT', 'POST'], allowedHeaders: ['X-Bazinga', 'X-Kittens', 'Authorization'], }) }) it('Returns the request origin, if cors origin is set to true', () => { const output = mapRwCorsOptionsToYoga( { origin: true, credentials: true, allowedHeaders: ['Auth-Provider', 'X-Kittens', 'Authorization'], methods: ['DELETE'], }, 'https://myapiside.redwood.com' // <-- this is the Request.headers.origin ) expect(output).toEqual({ credentials: true, origin: ['https://myapiside.redwood.com'], methods: ['DELETE'], allowedHeaders: ['Auth-Provider', 'X-Kittens', 'Authorization'], }) }) it('Returns the *, if cors origin is set to true AND no request origin supplied', () => { const output = mapRwCorsOptionsToYoga( { origin: true, credentials: true, allowedHeaders: ['Auth-Provider', 'X-Kittens', 'Authorization'], methods: ['DELETE'], }, undefined ) expect(output).toEqual({ credentials: true, origin: ['*'], methods: ['DELETE'], allowedHeaders: ['Auth-Provider', 'X-Kittens', 'Authorization'], }) }) })
5,497
0
petrpan-code/redwoodjs/redwood/packages/graphql-server/src/__tests__
petrpan-code/redwoodjs/redwood/packages/graphql-server/src/__tests__/__snapshots__/graphiql.test.ts.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`configureGraphiQLPlayground when in development should configure the GraphiQL Playground when allowGraphiQL is not provided 1`] = ` { "defaultQuery": "query Redwood { redwood { version } }", "headerEditorEnabled": true, "headers": undefined, "title": "Redwood GraphQL Playground", } `; exports[`configureGraphiQLPlayground when in development should configure the GraphiQL Playground when allowGraphiQL is null 1`] = ` { "defaultQuery": "query Redwood { redwood { version } }", "headerEditorEnabled": true, "headers": undefined, "title": "Redwood GraphQL Playground", } `; exports[`configureGraphiQLPlayground when in development should configure the GraphiQL Playground when allowGraphiQL is true 1`] = ` { "defaultQuery": "query Redwood { redwood { version } }", "headerEditorEnabled": true, "headers": undefined, "title": "Redwood GraphQL Playground", } `; exports[`configureGraphiQLPlayground when in development should configure the GraphiQL Playground when allowGraphiQL is undefined 1`] = ` { "defaultQuery": "query Redwood { redwood { version } }", "headerEditorEnabled": true, "headers": undefined, "title": "Redwood GraphQL Playground", } `; exports[`configureGraphiQLPlayground when in development should configure the GraphiQL Playground when no config is provided 1`] = ` { "defaultQuery": "query Redwood { redwood { version } }", "headerEditorEnabled": true, "headers": "{"x-auth-comment": "See documentation: https://redwoodjs.com/docs/cli-commands#setup-graphiql-headers on how to auto generate auth headers"}", "title": "Redwood GraphQL Playground", } `; exports[`configureGraphiQLPlayground when not in development environment should configure the GraphiQL Playground when allowGraphiQL is true 1`] = ` { "defaultQuery": "query Redwood { redwood { version } }", "headerEditorEnabled": true, "headers": undefined, "title": "Redwood GraphQL Playground", } `;
5,501
0
petrpan-code/redwoodjs/redwood/packages/graphql-server/src/functions
petrpan-code/redwoodjs/redwood/packages/graphql-server/src/functions/__tests__/authDecoders.test.ts
import type { APIGatewayProxyEvent, Context } from 'aws-lambda' import { createLogger } from '@redwoodjs/api/logger' import { createGraphQLHandler } from '../../functions/graphql' import { context } from '../../globalContext' jest.mock('../../makeMergedSchema', () => { const { makeExecutableSchema } = require('@graphql-tools/schema') // Return executable schema return { makeMergedSchema: () => makeExecutableSchema({ typeDefs: /* GraphQL */ ` type Query { me: User! } type User { firstName: String! lastName: String! id: ID! token: String! roles: [String!]! } `, resolvers: { Query: { me: () => { const globalContext = require('../../globalContext').context const currentUser = globalContext.currentUser return { firstName: 'Ba', lastName: 'Zinga', id: currentUser.userId, token: currentUser.token, roles: currentUser.roles, } }, }, }, }), } }) jest.mock('../../directives/makeDirectives', () => { return { makeDirectivesForPlugin: () => [], } }) type Decoded = Record<string, unknown> | null type Decoder = ( token: string, type: string, req: { event: APIGatewayProxyEvent context: Context } ) => Promise<Decoded> interface MockLambdaParams { headers?: { [key: string]: string } body?: string | null httpMethod: string [key: string]: any } const mockLambdaEvent = ({ headers, body = null, httpMethod, ...others }: MockLambdaParams): APIGatewayProxyEvent => { return { headers: headers || {}, body, httpMethod, multiValueQueryStringParameters: null, isBase64Encoded: false, multiValueHeaders: {}, // this is silly - the types require a value. It definitely can be undefined, e.g. on Vercel. path: '/graphql', pathParameters: null, stageVariables: null, queryStringParameters: null, requestContext: { accountId: 'MOCKED_ACCOUNT', apiId: 'MOCKED_API_ID', authorizer: { name: 'MOCKED_AUTHORIZER' }, protocol: 'HTTP', identity: { accessKey: null, accountId: null, apiKey: null, apiKeyId: null, caller: null, clientCert: null, cognitoAuthenticationProvider: null, cognitoAuthenticationType: null, cognitoIdentityId: null, cognitoIdentityPoolId: null, principalOrgId: null, sourceIp: '123.123.123.123', user: null, userAgent: null, userArn: null, }, httpMethod: 'POST', path: '/MOCK_PATH', stage: 'MOCK_STAGE', requestId: 'MOCKED_REQUEST_ID', requestTimeEpoch: 1, resourceId: 'MOCKED_RESOURCE_ID', resourcePath: 'MOCKED_RESOURCE_PATH', }, resource: 'MOCKED_RESOURCE', ...others, } } describe('createGraphQLHandler', () => { const adminAuthDecoder: Decoder = async (token, type) => { if (type !== 'admin-auth') { return null } return { userId: 'admin-one', token: token.replace(/-/g, ' '), } } const customerAuthDecoder: Decoder = async (token, type) => { if (type !== 'customer-auth') { return null } return { userId: 'customer-one', token: token.replace(/-/g, ' '), } } const getCurrentUser = async (decoded) => { if (decoded.userId === 'admin-one') { return { ...decoded, roles: ['admin'] } } else if (decoded.userId === 'customer-one') { return { ...decoded, roles: ['user'] } } } it('should allow you to pass an auth decoder', async () => { const handler = createGraphQLHandler({ getCurrentUser, authDecoder: adminAuthDecoder, loggerConfig: { logger: createLogger({}), options: {} }, sdls: {}, directives: {}, services: {}, onException: () => {}, }) const mockedEvent = mockLambdaEvent({ headers: { 'Content-Type': 'application/json', 'auth-provider': 'admin-auth', authorization: 'Bearer auth-test-token-admin', }, body: JSON.stringify({ query: '{ me { id, firstName, lastName, token, roles } }', }), httpMethod: 'POST', }) const response = await handler(mockedEvent, {} as Context) const body = JSON.parse(response.body) expect(body.data.me.id).toEqual('admin-one') expect(body.data.me.token).toEqual('auth test token admin') expect(body.data.me.roles).toEqual(['admin']) expect(response.statusCode).toBe(200) }) it('should allow you to pass an array of auth decoders, using the first one to decode', async () => { const handler = createGraphQLHandler({ getCurrentUser, authDecoder: [adminAuthDecoder, customerAuthDecoder], loggerConfig: { logger: createLogger({}), options: {} }, sdls: {}, directives: {}, services: {}, onException: () => {}, }) const mockedEvent = mockLambdaEvent({ headers: { 'Content-Type': 'application/json', 'auth-provider': 'admin-auth', authorization: 'Bearer auth-test-token-admin', }, body: JSON.stringify({ query: '{ me { id, firstName, lastName, token, roles } }', }), httpMethod: 'POST', }) const response = await handler(mockedEvent, {} as Context) const body = JSON.parse(response.body) expect(body.data.me.id).toEqual('admin-one') expect(body.data.me.token).toEqual('auth test token admin') expect(body.data.me.roles).toEqual(['admin']) expect(response.statusCode).toBe(200) }) it('should allow you to pass an array of auth decoders, using the second one to decode', async () => { const handler = createGraphQLHandler({ getCurrentUser, authDecoder: [adminAuthDecoder, customerAuthDecoder], loggerConfig: { logger: createLogger({}), options: {} }, sdls: {}, directives: {}, services: {}, onException: () => {}, }) const mockedEvent = mockLambdaEvent({ headers: { 'Content-Type': 'application/json', 'auth-provider': 'customer-auth', authorization: 'Bearer auth-test-token-customer', }, body: JSON.stringify({ query: '{ me { id, firstName, lastName, token, roles } }', }), httpMethod: 'POST', }) const response = await handler(mockedEvent, {} as Context) const body = JSON.parse(response.body) expect(body.data.me.id).toEqual('customer-one') expect(body.data.me.token).toEqual('auth test token customer') expect(body.data.me.roles).toEqual(['user']) expect(response.statusCode).toBe(200) }) })
5,502
0
petrpan-code/redwoodjs/redwood/packages/graphql-server/src/functions
petrpan-code/redwoodjs/redwood/packages/graphql-server/src/functions/__tests__/globalContext.test.ts
import { context as globalContext, setContext } from '../../globalContext' import { getAsyncStoreInstance } from '../../globalContextStore' describe('Global context with context isolation', () => { it('Should work when assigning directly into context', async () => { const asyncStore = getAsyncStoreInstance() asyncStore.run(new Map(), () => { // This is the actual test globalContext.myNewValue = 'bazinga' expect(globalContext.myNewValue).toBe('bazinga') }) // Check that context was isolated expect(globalContext.myNewValue).not.toBe('bazinga') }) it('Should work when using setContext', async () => { const asyncStore = getAsyncStoreInstance() asyncStore.run(new Map(), () => { // This is the actual test setContext({ anotherValue: 'kittens' }) expect(globalContext.anotherValue).toBe('kittens') }) // Check that context was isolated expect(globalContext.anotherValue).not.toBe('kittens') }) it('setContext replaces global context', async () => { const asyncStore = getAsyncStoreInstance() asyncStore.run(new Map(), () => { // This is the actual test globalContext.myNewValue = 'bazinga' setContext({ anotherValue: 'kittens' }) expect(globalContext.myNewValue).toBeUndefined() expect(globalContext.anotherValue).toBe('kittens') }) // Check that context was isolated expect(globalContext.myNewValue).toBeUndefined() expect(globalContext.anotherValue).toBeUndefined() }) })
5,503
0
petrpan-code/redwoodjs/redwood/packages/graphql-server/src/functions
petrpan-code/redwoodjs/redwood/packages/graphql-server/src/functions/__tests__/healthCheck.test.ts
import type { APIGatewayProxyEvent, Context } from 'aws-lambda' import { createLogger } from '@redwoodjs/api/logger' import { createGraphQLHandler } from '../../functions/graphql' jest.mock('../../makeMergedSchema', () => { const { makeExecutableSchema } = require('@graphql-tools/schema') // Return executable schema return { makeMergedSchema: () => makeExecutableSchema({ typeDefs: /* GraphQL */ ` type Query { me: User! } type User { id: ID! name: String! } `, resolvers: { Query: { me: () => { return { _id: 1, firstName: 'Ba', lastName: 'Zinga' } }, }, }, }), } }) jest.mock('../../directives/makeDirectives', () => { return { makeDirectivesForPlugin: () => [], } }) interface MockLambdaParams { headers?: { [key: string]: string } body?: string | null httpMethod: string [key: string]: any } const mockLambdaEvent = ({ headers, body = null, httpMethod, ...others }: MockLambdaParams): APIGatewayProxyEvent => { return { headers: headers || {}, body, httpMethod, multiValueQueryStringParameters: null, isBase64Encoded: false, multiValueHeaders: {}, // this is silly - the types require a value. It definitely can be undefined, e.g. on Vercel. path: '/graphql', pathParameters: null, stageVariables: null, queryStringParameters: null, requestContext: null as any, resource: null as any, ...others, } } describe('GraphQL Health Check', () => { describe('when making check with the default health check id', () => { it('returns ok, and the header has the default health check id', async () => { const handler = createGraphQLHandler({ loggerConfig: { logger: createLogger({}), options: {} }, sdls: {}, directives: {}, services: {}, onException: () => {}, }) const mockedEvent = mockLambdaEvent({ headers: { 'Content-Type': 'application/json', }, path: '/graphql/health', httpMethod: 'GET', }) const response = await handler(mockedEvent, {} as Context) expect(response.headers['x-yoga-id']).toBe('yoga') expect(response.statusCode).toBe(200) }) }) describe('when making check with a custom health check id', () => { it('returns ok, and the header has the custom health check id', async () => { const handler = createGraphQLHandler({ healthCheckId: 'custom-redwood-health-check', loggerConfig: { logger: createLogger({}), options: {} }, sdls: {}, directives: {}, services: {}, onException: () => {}, }) const mockedEvent = mockLambdaEvent({ headers: { 'Content-Type': 'application/json', }, path: '/graphql/health', httpMethod: 'GET', }) const response = await handler(mockedEvent, {} as Context) expect(response.headers['x-yoga-id']).toBe('custom-redwood-health-check') expect(response.statusCode).toBe(200) }) }) })
5,504
0
petrpan-code/redwoodjs/redwood/packages/graphql-server/src/functions
petrpan-code/redwoodjs/redwood/packages/graphql-server/src/functions/__tests__/normalizeRequest.test.ts
import { Headers } from '@whatwg-node/fetch' import type { APIGatewayProxyEvent } from 'aws-lambda' import { normalizeRequest } from '@redwoodjs/api' export const createMockedEvent = ( httpMethod = 'POST', body: any = undefined, isBase64Encoded = false ): APIGatewayProxyEvent => { return { body, headers: {}, multiValueHeaders: {}, httpMethod, isBase64Encoded, path: '/MOCK_PATH', pathParameters: null, queryStringParameters: null, multiValueQueryStringParameters: null, stageVariables: null, requestContext: { accountId: 'MOCKED_ACCOUNT', apiId: 'MOCKED_API_ID', authorizer: { name: 'MOCKED_AUTHORIZER' }, protocol: 'HTTP', identity: { accessKey: null, accountId: null, apiKey: null, apiKeyId: null, caller: null, clientCert: null, cognitoAuthenticationProvider: null, cognitoAuthenticationType: null, cognitoIdentityId: null, cognitoIdentityPoolId: null, principalOrgId: null, sourceIp: '123.123.123.123', user: null, userAgent: null, userArn: null, }, httpMethod: 'POST', path: '/MOCK_PATH', stage: 'MOCK_STAGE', requestId: 'MOCKED_REQUEST_ID', requestTimeEpoch: 1, resourceId: 'MOCKED_RESOURCE_ID', resourcePath: 'MOCKED_RESOURCE_PATH', }, resource: 'MOCKED_RESOURCE', } } test('Normalizes an aws event with base64', () => { const corsEventB64 = createMockedEvent( 'POST', Buffer.from(JSON.stringify({ bazinga: 'hello_world' }), 'utf8').toString( 'base64' ), true ) const normalizedRequest = normalizeRequest(corsEventB64) const expectedRequest = { headers: new Headers(corsEventB64.headers), method: 'POST', query: null, body: { bazinga: 'hello_world', }, } expect(normalizedRequest.method).toEqual(expectedRequest.method) expect(normalizedRequest.query).toEqual(expectedRequest.query) expect(normalizedRequest.body).toEqual(expectedRequest.body) expectedRequest.headers.forEach((value, key) => { expect(normalizedRequest.headers.get(key)).toEqual(value) }) }) test('Handles CORS requests with and without b64 encoded', () => { const corsEventB64 = createMockedEvent('OPTIONS', undefined, true) const normalizedRequest = normalizeRequest(corsEventB64) const expectedRequest = { headers: new Headers(corsEventB64.headers), method: 'OPTIONS', query: null, body: undefined, } expect(normalizedRequest.method).toEqual(expectedRequest.method) expect(normalizedRequest.query).toEqual(expectedRequest.query) expect(normalizedRequest.body).toEqual(expectedRequest.body) expectedRequest.headers.forEach((value, key) => { expect(normalizedRequest.headers.get(key)).toEqual(value) }) })
5,505
0
petrpan-code/redwoodjs/redwood/packages/graphql-server/src/functions
petrpan-code/redwoodjs/redwood/packages/graphql-server/src/functions/__tests__/readinessCheck.test.ts
import type { APIGatewayProxyEvent, Context } from 'aws-lambda' import { createLogger } from '@redwoodjs/api/logger' import { createGraphQLHandler } from '../../functions/graphql' jest.mock('../../makeMergedSchema', () => { const { makeExecutableSchema } = require('@graphql-tools/schema') // Return executable schema return { makeMergedSchema: () => makeExecutableSchema({ typeDefs: /* GraphQL */ ` type Query { me: User! } type User { id: ID! name: String! } `, resolvers: { Query: { me: () => { return { _id: 1, firstName: 'Ba', lastName: 'Zinga' } }, }, }, }), } }) jest.mock('../../directives/makeDirectives', () => { return { makeDirectivesForPlugin: () => [], } }) interface MockLambdaParams { headers?: { [key: string]: string } body?: string | null httpMethod: string [key: string]: any } const mockLambdaEvent = ({ headers, body = null, httpMethod, ...others }: MockLambdaParams): APIGatewayProxyEvent => { return { headers: headers || {}, body, httpMethod, multiValueQueryStringParameters: null, isBase64Encoded: false, multiValueHeaders: {}, // this is silly - the types require a value. It definitely can be undefined, e.g. on Vercel. path: '/graphql', pathParameters: null, stageVariables: null, queryStringParameters: null, requestContext: null as any, resource: null as any, ...others, } } describe('GraphQL Readiness Check', () => { describe('when making a check for the default health check id to determine readiness', () => { it('returns ok', async () => { const handler = createGraphQLHandler({ loggerConfig: { logger: createLogger({}), options: {} }, sdls: {}, directives: {}, services: {}, onException: () => {}, }) const mockedEvent = mockLambdaEvent({ headers: { 'x-yoga-id': 'yoga', 'Content-Type': 'application/json', }, path: '/graphql/readiness', httpMethod: 'GET', }) const response = await handler(mockedEvent, {} as Context) expect(response.statusCode).toBe(200) }) it('returns 503 if the default health check id does not match', async () => { const handler = createGraphQLHandler({ loggerConfig: { logger: createLogger({}), options: {} }, sdls: {}, directives: {}, services: {}, onException: () => {}, }) const mockedEvent = mockLambdaEvent({ headers: { 'x-yoga-id': 'wrong-custom-health-check-id', 'Content-Type': 'application/json', }, path: '/graphql/readiness', httpMethod: 'GET', }) const response = await handler(mockedEvent, {} as Context) expect(response.statusCode).toBe(503) }) }) describe('when making a check with a custom health check id to determine readiness', () => { it('returns ok', async () => { const handler = createGraphQLHandler({ healthCheckId: 'custom-health-check-id', loggerConfig: { logger: createLogger({}), options: {} }, sdls: {}, directives: {}, services: {}, onException: () => {}, }) const mockedEvent = mockLambdaEvent({ headers: { 'x-yoga-id': 'custom-health-check-id', 'Content-Type': 'application/json', }, path: '/graphql/readiness', httpMethod: 'GET', }) const response = await handler(mockedEvent, {} as Context) expect(response.statusCode).toBe(200) }) it('returns 503 if the health check id does not match', async () => { const handler = createGraphQLHandler({ healthCheckId: 'custom-health-check-id', loggerConfig: { logger: createLogger({}), options: {} }, sdls: {}, directives: {}, services: {}, onException: () => {}, }) const mockedEvent = mockLambdaEvent({ headers: { 'x-yoga-id': 'wrong-custom-health-check-id', 'Content-Type': 'application/json', }, path: '/graphql/readiness', httpMethod: 'GET', }) const response = await handler(mockedEvent, {} as Context) expect(response.statusCode).toBe(503) }) }) })
5,506
0
petrpan-code/redwoodjs/redwood/packages/graphql-server/src/functions
petrpan-code/redwoodjs/redwood/packages/graphql-server/src/functions/__tests__/useRequireAuth.test.ts
import type { APIGatewayEvent, Context } from 'aws-lambda' import jwt from 'jsonwebtoken' import { AuthenticationError } from '../../errors' import type { UseRequireAuth } from '../useRequireAuth' import { getCurrentUser } from './fixtures/auth' type RedwoodUser = Record<string, unknown> & { roles?: string[] } export const mockedAuthenticationEvent = ({ headers = {}, }: { headers: Record<string, any> | null | undefined }): APIGatewayEvent => { return { body: 'MOCKED_BODY', headers: headers || {}, multiValueHeaders: {}, httpMethod: 'POST', isBase64Encoded: false, path: '/MOCK_PATH', pathParameters: null, queryStringParameters: null, multiValueQueryStringParameters: null, stageVariables: null, requestContext: { accountId: 'MOCKED_ACCOUNT', apiId: 'MOCKED_API_ID', authorizer: { name: 'MOCKED_AUTHORIZER' }, protocol: 'HTTP', identity: { accessKey: null, accountId: null, apiKey: null, apiKeyId: null, caller: null, clientCert: null, cognitoAuthenticationProvider: null, cognitoAuthenticationType: null, cognitoIdentityId: null, cognitoIdentityPoolId: null, principalOrgId: null, sourceIp: '123.123.123.123', user: null, userAgent: null, userArn: null, }, httpMethod: 'POST', path: '/MOCK_PATH', stage: 'MOCK_STAGE', requestId: 'MOCKED_REQUEST_ID', requestTimeEpoch: 1, resourceId: 'MOCKED_RESOURCE_ID', resourcePath: 'MOCKED_RESOURCE_PATH', }, resource: 'MOCKED_RESOURCE', } } const handler = async ( _event: APIGatewayEvent, _context: Context ): Promise<any> => { // @MARK // Don't use globalContext until beforeAll runs const globalContext = require('../../globalContext').context const currentUser = globalContext.currentUser return { statusCode: 200, headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ currentUser: currentUser || 'NO_CURRENT_USER' }), } } const handlerWithAuthChecks = async ( _event: APIGatewayEvent, _context: Context ): Promise<unknown> => { // TODO: Add requireAuth('role') here // or isAuthenticated() const { hasRole, isAuthenticated, requireAuth } = require('./fixtures/auth') const body = { message: '', } if (!isAuthenticated()) { body.message = 'Not authenticated' } else if (hasRole('admin')) { body.message = 'User is an admin' } else { requireAuth({ roles: 'editor' }) body.message = 'User is an editor' } return { statusCode: 200, headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(body), } } const handlerWithError = async ( _event: APIGatewayEvent, _context: Context ): Promise<any> => { // @MARK // Don't use globalContext until beforeAll runs const globalContext = require('../../globalContext').context const currentUser = globalContext.currentUser try { throw new AuthenticationError('An error occurred in the handler') return { statusCode: 200, headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(currentUser), } } catch (error) { return { statusCode: 500, headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ error: error.message }), } } } const getCurrentUserWithError = async ( _decoded, { token: _token } ): Promise<RedwoodUser> => { throw Error('Something went wrong getting the user info') } describe('useRequireAuth', () => { it('Updates context with output of current user', async () => { // @MARK // Because we use context inside useRequireAuth, we only want to import this function // once we disable context isolation for our test const { useRequireAuth, }: { useRequireAuth: UseRequireAuth } = require('../useRequireAuth') const handlerEnrichedWithAuthentication = useRequireAuth({ handlerFn: handler, getCurrentUser, authDecoder: async ( token: string, _type: string, _req: { event: APIGatewayEvent; context: Context } ) => { return { token } }, }) const headers = { 'auth-provider': 'custom', authorization: 'Bearer myToken', } const output = await handlerEnrichedWithAuthentication( mockedAuthenticationEvent({ headers }), {} as Context ) const response = JSON.parse(output.body) expect(response.currentUser.token).toEqual('myToken') }) it('Updates context with output of current user with roles', async () => { // @MARK // Because we use context inside useRequireAuth, we only want to import this function // once we disable context isolation for our test const { useRequireAuth, }: { useRequireAuth: UseRequireAuth } = require('../useRequireAuth') const handlerEnrichedWithAuthentication = useRequireAuth({ handlerFn: handler, getCurrentUser, authDecoder: async ( token: string, _type: string, _req: { event: APIGatewayEvent; context: Context } ) => { return jwt.decode(token) as Record<string, any> }, }) // The authorization JWT is valid and has roles in app metadata // { // "sub": "1234567891", // "name": "John Editor", // "iat": 1516239022, // "app_metadata": { // "roles": ["editor"] // } // } const headersWithRoles = { 'auth-provider': 'netlify', authorization: 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkxIiwibmFtZSI6IkpvaG4gRWRpdG9yIiwiaWF0IjoxNTE2MjM5MDIyLCJhcHBfbWV0YWRhdGEiOnsicm9sZXMiOlsiZWRpdG9yIl19fQ.Fhxe58-7BcjJDoYQAZluJYGwPTPLU0x6K5yA3zXKaX8', } const output = await handlerEnrichedWithAuthentication( mockedAuthenticationEvent({ headers: headersWithRoles }), {} as Context ) const response = JSON.parse(output.body) expect(response.currentUser.name).toEqual('John Editor') expect(response.currentUser.roles).toContain('editor') }) it('is 200 status if an error occurs when getting current user info', async () => { const { useRequireAuth, }: { useRequireAuth: UseRequireAuth } = require('../useRequireAuth') const handlerEnrichedWithAuthentication = useRequireAuth({ handlerFn: handler, getCurrentUser: getCurrentUserWithError, }) const customHeaders = { 'auth-provider': 'custom', authorization: 'Bearer myToken', } const output = await handlerEnrichedWithAuthentication( mockedAuthenticationEvent({ headers: customHeaders }), {} as Context ) expect(output.statusCode).toEqual(200) const response = JSON.parse(output.body) expect(response.currentUser).toEqual('NO_CURRENT_USER') }) it('is 200 status if no auth headers present', async () => { const { useRequireAuth, }: { useRequireAuth: UseRequireAuth } = require('../useRequireAuth') const handlerEnrichedWithAuthentication = useRequireAuth({ handlerFn: handler, getCurrentUser, authDecoder: async ( _token: string, _type: string, _req: { event: APIGatewayEvent; context: Context } ) => { return null }, }) const missingHeaders = null const output = await handlerEnrichedWithAuthentication( mockedAuthenticationEvent({ headers: missingHeaders }), {} as Context ) expect(output.statusCode).toEqual(200) const response = JSON.parse(output.body) expect(response.currentUser).toEqual('NO_CURRENT_USER') }) it('is 200 status with token if the auth provider is unsupported', async () => { const { useRequireAuth, }: { useRequireAuth: UseRequireAuth } = require('../useRequireAuth') const handlerEnrichedWithAuthentication = useRequireAuth({ handlerFn: handler, getCurrentUser, authDecoder: async ( token: string, _type: string, _req: { event: APIGatewayEvent; context: Context } ) => { return { token } }, }) const unsupportedProviderHeaders = { 'auth-provider': 'this-auth-provider-is-unsupported', authorization: 'Basic myToken', } const response = await handlerEnrichedWithAuthentication( mockedAuthenticationEvent({ headers: unsupportedProviderHeaders }), {} as Context ) const body = JSON.parse(response.body) expect(response.statusCode).toEqual(200) expect(body.currentUser.token).toEqual('myToken') }) it('returns 200 if decoding JWT succeeds for netlify', async () => { const { useRequireAuth, }: { useRequireAuth: UseRequireAuth } = require('../useRequireAuth') const handlerEnrichedWithAuthentication = useRequireAuth({ handlerFn: handler, getCurrentUser, authDecoder: async ( token: string, _type: string, _req: { event: APIGatewayEvent; context: Context } ) => { return jwt.decode(token) as Record<string, any> }, }) // Note: The Bearer token JWT contains: // { // "sub": "1234567890", // "name": "John Doe", // "iat": 1516239022 // } const netlifyJWTHeaders = { 'auth-provider': 'netlify', authorization: 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c', } const response = await handlerEnrichedWithAuthentication( mockedAuthenticationEvent({ headers: netlifyJWTHeaders }), {} as Context ) const body = JSON.parse(response.body) expect(response.statusCode).toEqual(200) expect(body.currentUser.sub).toEqual('1234567890') expect(body.currentUser.name).toEqual('John Doe') }) it('is 200 status if decoding JWT fails for netlify', async () => { const { useRequireAuth, }: { useRequireAuth: UseRequireAuth } = require('../useRequireAuth') const handlerEnrichedWithAuthentication = useRequireAuth({ handlerFn: handler, getCurrentUser, }) const invalidJWTHeaders = { 'auth-provider': 'netlify', authorization: 'Bearer this-is-an-invalid-jwt', } const response = await handlerEnrichedWithAuthentication( mockedAuthenticationEvent({ headers: invalidJWTHeaders }), {} as Context ) const body = JSON.parse(response.body) expect(response.statusCode).toEqual(200) expect(body.currentUser).toEqual('NO_CURRENT_USER') }) it('is 200 status if decoding JWT fails for supabase', async () => { const { useRequireAuth, }: { useRequireAuth: UseRequireAuth } = require('../useRequireAuth') const handlerEnrichedWithAuthentication = useRequireAuth({ handlerFn: handler, getCurrentUser, }) const invalidJWTHeaders = { 'auth-provider': 'supabase', authorization: 'Bearer this-is-an-invalid-jwt', } const response = await handlerEnrichedWithAuthentication( mockedAuthenticationEvent({ headers: invalidJWTHeaders }), {} as Context ) const body = JSON.parse(response.body) expect(response.statusCode).toEqual(200) expect(body.currentUser).toEqual('NO_CURRENT_USER') }) it('is 500 Server Error status if handler errors', async () => { const { useRequireAuth, }: { useRequireAuth: UseRequireAuth } = require('../useRequireAuth') const customHeaders = { 'auth-provider': 'custom', authorization: 'Bearer myToken', } const handlerEnrichedWithAuthentication = useRequireAuth({ handlerFn: handlerWithError, getCurrentUser, }) const response = await handlerEnrichedWithAuthentication( mockedAuthenticationEvent({ headers: customHeaders }), {} as Context ) const message = JSON.parse(response.body).error expect(response.statusCode).toEqual(500) expect(message).toEqual('An error occurred in the handler') }) it('enables the use of auth functions inside the handler to check that isAuthenticated blocks unauthenticated users', async () => { const { useRequireAuth, }: { useRequireAuth: UseRequireAuth } = require('../useRequireAuth') const netlifyJWTHeaders = { 'auth-provider': 'netlify', authorization: 'Bearer eyJhbGciOi.eyJzdWI.Sfl_expired_token', } const handlerEnrichedWithAuthentication = useRequireAuth({ handlerFn: handlerWithAuthChecks, getCurrentUser, }) const response = await handlerEnrichedWithAuthentication( mockedAuthenticationEvent({ headers: netlifyJWTHeaders }), {} as Context ) const body = JSON.parse(response.body) expect(response.statusCode).toEqual(200) expect(body.message).toEqual('Not authenticated') }) it("enables the use of auth functions inside the handler to check that requireAuth throws if the user doesn't have the required role", async () => { const { useRequireAuth, }: { useRequireAuth: UseRequireAuth } = require('../useRequireAuth') // Note: The Bearer token JWT contains: // { // "sub": "1234567890", // "name": "John Doe", // "iat": 1516239022 // } const netlifyJWTHeaders = { 'auth-provider': 'netlify', authorization: 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c', } const handlerEnrichedWithAuthentication = useRequireAuth({ handlerFn: handlerWithAuthChecks, getCurrentUser, authDecoder: async ( token: string, _type: string, _req: { event: APIGatewayEvent; context: Context } ) => { return jwt.decode(token) as Record<string, any> }, }) await expect( handlerEnrichedWithAuthentication( mockedAuthenticationEvent({ headers: netlifyJWTHeaders }), {} as Context ) ).rejects.toThrow("You don't have access to do that.") }) it('enables the use of auth functions inside the handler to check editor role', async () => { const { useRequireAuth, }: { useRequireAuth: UseRequireAuth } = require('../useRequireAuth') // The authorization JWT is valid and has roles in app metadata // { // "sub": "1234567891", // "name": "John Editor", // "iat": 1516239022, // "app_metadata": { // "roles": ["editor"] // } // } const headersWithRoles = { 'auth-provider': 'netlify', authorization: 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkxIiwibmFtZSI6IkpvaG4gRWRpdG9yIiwiaWF0IjoxNTE2MjM5MDIyLCJhcHBfbWV0YWRhdGEiOnsicm9sZXMiOlsiZWRpdG9yIl19fQ.Fhxe58-7BcjJDoYQAZluJYGwPTPLU0x6K5yA3zXKaX8', } const handlerEnrichedWithAuthentication = useRequireAuth({ handlerFn: handlerWithAuthChecks, getCurrentUser, authDecoder: async ( token: string, _type: string, _req: { event: APIGatewayEvent; context: Context } ) => { return jwt.decode(token) as Record<string, any> }, }) const response = await handlerEnrichedWithAuthentication( mockedAuthenticationEvent({ headers: headersWithRoles }), {} as Context ) const body = JSON.parse(response.body) expect(response.statusCode).toEqual(200) expect(body.message).toEqual('User is an editor') }) })
5,519
0
petrpan-code/redwoodjs/redwood/packages/graphql-server/src/plugins
petrpan-code/redwoodjs/redwood/packages/graphql-server/src/plugins/__tests__/useArmor.test.ts
import type { APIGatewayProxyEvent, Context } from 'aws-lambda' import { createLogger } from '@redwoodjs/api/logger' import { createGraphQLHandler } from '../../functions/graphql' jest.mock('../../makeMergedSchema', () => { const { makeExecutableSchema } = require('@graphql-tools/schema') // Return executable schema return { makeMergedSchema: () => makeExecutableSchema({ typeDefs: /* GraphQL */ ` type Author { id: Int! name: String! posts: [Post] } type Post { id: Int! title: String! body: String! author: Author } type Query { author: Author posts: [Post!]! post(id: Int!): Post } `, resolvers: { Query: { author: () => { return { id: 1, name: 'Bob', posts: [{ id: 1, title: 'Ba', body: 'Zinga' }], } }, posts: () => { return [ { id: 1, title: 'Ba', body: 'Zinga', author: { id: 1, name: 'Bob' }, }, ] }, post: (id) => { return { id, title: 'Ba', body: 'Zinga', author: { id: 1, name: 'Bob' }, } }, }, }, }), } }) jest.mock('../../directives/makeDirectives', () => { return { makeDirectivesForPlugin: () => [], } }) interface MockLambdaParams { headers?: { [key: string]: string } body?: string | null httpMethod: string [key: string]: any } const mockLambdaEvent = ({ headers, body = null, httpMethod, ...others }: MockLambdaParams): APIGatewayProxyEvent => { return { headers: headers || {}, body, httpMethod, multiValueQueryStringParameters: null, isBase64Encoded: false, multiValueHeaders: {}, // this is silly - the types require a value. It definitely can be undefined, e.g. on Vercel. path: '/graphql', pathParameters: null, stageVariables: null, queryStringParameters: null, requestContext: null as any, resource: null as any, ...others, } } describe('useArmor secures the GraphQLHandler endpoint for depth, aliases, cost, and other optimistic protections', () => { const createHandler = (armorConfig) => { return createGraphQLHandler({ armorConfig, loggerConfig: { logger: createLogger({}), options: {}, }, sdls: {}, directives: {}, services: {}, onException: () => {}, }) } const mockedEvent = mockLambdaEvent({ headers: { 'Content-Type': 'application/json', }, httpMethod: 'POST', }) const mockQuery = (query) => { const event = mockedEvent mockedEvent.body = JSON.stringify({ query }) return event } const mockGraphQLRequest = async (query, armorConfig?) => { const handler = createHandler(armorConfig) return await handler(mockQuery(query), {} as Context) } describe('when blocking field suggestion', () => { describe('with defaults', () => { it('returns the field suggestion masked', async () => { const query = '{ posts { id, toootle } }' const response = await mockGraphQLRequest(query) const { data, errors } = JSON.parse(response.body) expect(response.statusCode).toBe(200) expect(data).toBeUndefined() expect(errors[0].message).toMatchInlineSnapshot( '"Cannot query field "toootle" on type "Post". [Suggestion hidden]?"' ) }) }) describe('when disabled', () => { it('returns the field suggestion', async () => { const query = '{ posts { id, toootle } }' const armorConfig = { blockFieldSuggestion: { enabled: false }, } const response = await mockGraphQLRequest(query, armorConfig) const { data, errors } = JSON.parse(response.body) expect(response.statusCode).toBe(200) expect(data).toBeUndefined() expect(errors[0].message).toMatchInlineSnapshot( '"Cannot query field "toootle" on type "Post". Did you mean "title"?"' ) }) }) describe('with a custom suggestion mask', () => { it('returns the field suggestion masked with the custom masking', async () => { const query = '{ posts { id, toootle } }' const armorConfig = { blockFieldSuggestion: { mask: '<REDACTED>' }, } const response = await mockGraphQLRequest(query, armorConfig) const { data, errors } = JSON.parse(response.body) expect(response.statusCode).toBe(200) expect(data).toBeUndefined() expect(errors[0].message).toMatchInlineSnapshot( '"Cannot query field "toootle" on type "Post". <REDACTED>?"' ) }) }) }) describe('when enforcing max query depth', () => { describe('with defaults', () => { it('returns depth warning message', async () => { const query = ` { posts { id title author { id posts { id author { id posts { id author { id posts { id } } } } } } } }` const response = await mockGraphQLRequest(query) const { data, errors } = JSON.parse(response.body) expect(response.statusCode).toBe(200) expect(data).toBeUndefined() expect(errors[0].message).toMatchInlineSnapshot( '"Syntax Error: Query depth limit of 6 exceeded, found 8."' ) }) }) describe('when disabled', () => { it('returns no errors', async () => { const query = ` { posts { id title author { id posts { id author { id posts { id author { id posts { id } } } } } } } }` const armorConfig = { maxDepth: { enabled: false }, } const response = await mockGraphQLRequest(query, armorConfig) const { data, errors } = JSON.parse(response.body) expect(data.posts).toBeDefined() expect(response.statusCode).toBe(200) expect(errors).toBeUndefined() }) }) describe('with a custom depth', () => { it('returns the depth warning with the custom level', async () => { const query = ` { posts { id title author { id posts { id author { id posts { id author { id posts { id } } } } } } } }` const armorConfig = { maxDepth: { n: 4 }, } const response = await mockGraphQLRequest(query, armorConfig) const { data, errors } = JSON.parse(response.body) expect(response.statusCode).toBe(200) expect(data).toBeUndefined() expect(errors[0].message).toMatchInlineSnapshot( '"Syntax Error: Query depth limit of 4 exceeded, found 8."' ) }) }) }) describe('when enforcing the number of aliases in a GraphQL document', () => { describe('with defaults', () => { it('allows up to 15', async () => { const query = ` { postsAlias1: posts { id id1: id id2: id id3: id id4: id id5: id title title1: title title2: title title3: title title4: title title5: title } }` const response = await mockGraphQLRequest(query) const { data, errors } = JSON.parse(response.body) expect(response.statusCode).toBe(200) expect(data.postsAlias1[0].id1).toEqual(1) expect(errors).toBeUndefined() }) it('protects when more than 15 aliases', async () => { const query = ` { postsAlias1: posts { id id1: id id2: id id3: id id4: id id5: id id6: id id7: id id8: id id9: id id10: id title title1: title title2: title title3: title title4: title title5: title title6: title title7: title title8: title title9: title title10: title } }` const response = await mockGraphQLRequest(query) const { data, errors } = JSON.parse(response.body) expect(response.statusCode).toBe(200) expect(data).toBeUndefined() expect(errors[0].message).toMatchInlineSnapshot( '"Syntax Error: Aliases limit of 15 exceeded, found 21."' ) }) }) describe('when disabled', () => { it('returns no errors', async () => { const query = ` { postsAlias1: posts { id id1: id id2: id id3: id id4: id id5: id id6: id id7: id id8: id id9: id id10: id title title1: title title2: title title3: title title4: title title5: title title6: title title7: title title8: title title9: title title10: title } }` const armorConfig = { maxAliases: { enabled: false }, } const response = await mockGraphQLRequest(query, armorConfig) const { data, errors } = JSON.parse(response.body) expect(response.statusCode).toBe(200) expect(errors).toBeUndefined() expect(data.postsAlias1[0].id1).toEqual(1) }) }) describe('wtih a custom alias maximum', () => { it('protects at that level', async () => { const query = ` { postsAlias1: posts { id id1: id id2: id title title1: title title2: title title3: title } }` const armorConfig = { maxAliases: { n: 3 }, } const response = await mockGraphQLRequest(query, armorConfig) const { data, errors } = JSON.parse(response.body) expect(response.statusCode).toBe(200) expect(data).toBeUndefined() expect(errors[0].message).toMatchInlineSnapshot( '"Syntax Error: Aliases limit of 3 exceeded, found 6."' ) }) }) }) /** * Parsing a GraphQL operation document is a very expensive and compute intensive operation that blocks the JavaScript event loop. * If an attacker sends a very complex operation document with slight variations over and over again he can easily degrade the performance of the GraphQL server. * Because of the variations simply having an LRU cache for parsed operation documents is not enough. * * A potential solution is to limit the maximal allowed count of tokens within a GraphQL document. * * In computer science, lexical analysis, lexing or tokenization is the process of converting a sequence of characters into a sequence of lexical tokens. * E.g. given the following GraphQL operation. * * graphql { * me { * id * user * } * } * * The tokens are query, {, me, {, id, user, } and }. Having a total count of 8 tokens. * The optimal maximum token count for your application depends on the complexity of the GrapHQL operations and documents. Usually 800-2000 tokens seems like a sane default. * * GraphQL Armor provides a default maximum token count of 1000 tokens. * * Note: When reporting the number of found tokens as in * * '"Syntax Error: Token limit of 2 exceeded."' * * */ describe('when protecting against token complexity', () => { describe('with a custom max', () => { it('enforces a smaller limit', async () => { const query = '{ posts { id, title } }' const armorConfig = { maxTokens: { n: 2 }, } const response = await mockGraphQLRequest(query, armorConfig) const { data, errors } = JSON.parse(response.body) expect(response.statusCode).toBe(200) expect(data).toBeUndefined() expect(errors[0].message).toMatchInlineSnapshot( '"Syntax Error: Token limit of 2 exceeded."' ) }) }) }) describe('when protecting maximum directives', () => { describe('with defaults', () => { it('cannot apply an unknown directive', async () => { const query = '{ __typename @a @a @a @a }' const response = await mockGraphQLRequest(query) const { data, errors } = JSON.parse(response.body) expect(response.statusCode).toBe(200) expect(data).toBeUndefined() expect(errors[0].message).toMatchInlineSnapshot( '"Unknown directive "@a"."' ) }) }) describe('when disabled', () => { it('cannot apply an unknown directive', async () => { const query = '{ __typename @a @a @a @a }' const armorConfig = { maxDirectives: { enabled: false }, } const response = await mockGraphQLRequest(query, armorConfig) const { data, errors } = JSON.parse(response.body) expect(response.statusCode).toBe(200) expect(data).toBeUndefined() expect(errors[0].message).toMatchInlineSnapshot( '"Unknown directive "@a"."' ) }) }) describe('with a custom max', () => { it('enforces a smaller limit', async () => { const query = '{ __typename @a @a @a @a }' const armorConfig = { maxDirectives: { n: 2 }, } const response = await mockGraphQLRequest(query, armorConfig) const { data, errors } = JSON.parse(response.body) expect(response.statusCode).toBe(200) expect(data).toBeUndefined() expect(errors[0].message).toMatchInlineSnapshot( '"Syntax Error: Directives limit of 2 exceeded, found 4."' ) }) }) }) describe('when protecting cost limit', () => { describe('with defaults', () => { it('allows basic queries', async () => { const query = '{ posts { id, title } }' const response = await mockGraphQLRequest(query) const { data, errors } = JSON.parse(response.body) expect(response.statusCode).toBe(200) expect(data).toBeDefined() expect(data.posts[0]).toEqual({ id: 1, title: 'Ba' }) expect(errors).toBeUndefined() }) }) describe('when disabled', () => { it('allows a more costly limit', async () => { const query = '{ posts { id, title } }' const armorConfig = { costLimit: { enabled: false, objectCost: 5000 }, } const response = await mockGraphQLRequest(query, armorConfig) const { data, errors } = JSON.parse(response.body) expect(response.statusCode).toBe(200) expect(errors).toBeUndefined() expect(data.posts[0]).toEqual({ id: 1, title: 'Ba' }) }) }) describe('with a custom max', () => { it('enforces a smaller limit', async () => { const query = '{ posts { id, title } }' const armorConfig = { costLimit: { maxCost: 1 }, } // we have two scalars id and title worth 1 each // that's 2 at a level 1 with a factor of 1.5 // 2 * (1 * 1.5) = 3 // it's parent object of posts and worth 2 // so 3 + 2 = 5 total cost const response = await mockGraphQLRequest(query, armorConfig) const { data, errors } = JSON.parse(response.body) expect(response.statusCode).toBe(200) expect(data).toBeUndefined() expect(errors[0].message).toMatchInlineSnapshot( '"Syntax Error: Query Cost limit of 1 exceeded, found 5."' ) }) }) describe('with a custom calculation', () => { it('enforces a larger scalar cost', async () => { const query = '{ posts { id, title } }' const armorConfig = { costLimit: { maxCost: 10, scalarCost: 7 }, } // we have two scalars id and title worth 7 each // that's 14 at a level 1 with a factor of 1.5 // 14 * (1 * 1.5) = 21 // it's parent object of posts and worth 2 // so 21 + 2 = 23 total cost const response = await mockGraphQLRequest(query, armorConfig) const { data, errors } = JSON.parse(response.body) expect(response.statusCode).toBe(200) expect(data).toBeUndefined() expect(errors[0].message).toMatchInlineSnapshot( '"Syntax Error: Query Cost limit of 10 exceeded, found 23."' ) }) it('enforces a larger object cost', async () => { const query = '{ posts { id, title } }' const armorConfig = { costLimit: { maxCost: 2000, objectCost: 5000 }, } // we have two scalars id and title worth 1 each // that's 2 at a level 1 with a factor of 1.5 // 2 * (1 * 1.5) = 3 // it's parent object of posts and worth 5000 // so 3 + 500 = 5003 total cost const response = await mockGraphQLRequest(query, armorConfig) const { data, errors } = JSON.parse(response.body) expect(response.statusCode).toBe(200) expect(data).toBeUndefined() expect(errors[0].message).toMatchInlineSnapshot( '"Syntax Error: Query Cost limit of 2000 exceeded, found 5003."' ) }) }) it('enforces a larger depthCostFactor cost', async () => { const query = '{ posts { id, title } }' const armorConfig = { costLimit: { maxCost: 20, depthCostFactor: 11 }, } // we have two scalars id and title worth 1 each // that's 2 at a level 1 with a factor of 1.5 // 2 * (1 * 11) = 22 // it's parent object of posts and worth 2 // so 22 + 2 = 24 total cost const response = await mockGraphQLRequest(query, armorConfig) const { data, errors } = JSON.parse(response.body) expect(response.statusCode).toBe(200) expect(data).toBeUndefined() expect(errors[0].message).toMatchInlineSnapshot( '"Syntax Error: Query Cost limit of 20 exceeded, found 24."' ) }) }) })
5,520
0
petrpan-code/redwoodjs/redwood/packages/graphql-server/src/plugins
petrpan-code/redwoodjs/redwood/packages/graphql-server/src/plugins/__tests__/useRedwoodAuthContext.test.ts
import { useEngine } from '@envelop/core' import { createSpiedPlugin, createTestkit } from '@envelop/testing' import * as GraphQLJS from 'graphql' import { testSchema, testQuery } from '../__fixtures__/common' import { useRedwoodAuthContext } from '../useRedwoodAuthContext' const authDecoder = async (token: string) => ({ token }) jest.mock('@redwoodjs/api', () => { return { ...jest.requireActual('@redwoodjs/api'), getAuthenticationContext: jest.fn().mockResolvedValue([ { sub: '1', email: '[email protected]' }, { type: 'mocked-auth-type', schema: 'mocked-schema-bearer', token: 'mocked-undecoded-token', }, { event: {}, context: {} }, ]), } }) describe('useRedwoodAuthContext', () => { const spiedPlugin = createSpiedPlugin() const expectContextContains = (obj) => { expect(spiedPlugin.spies.beforeContextBuilding).toHaveBeenCalledWith( expect.objectContaining({ context: expect.objectContaining(obj), }) ) } beforeEach(() => { spiedPlugin.reset() }) it('Updates context with output of current user', async () => { const MOCK_USER = { id: 'my-user-id', name: 'Mockity MockFace', } const mockedGetCurrentUser = jest.fn().mockResolvedValue(MOCK_USER) const testkit = createTestkit( [ useEngine(GraphQLJS), useRedwoodAuthContext(mockedGetCurrentUser, authDecoder), spiedPlugin.plugin, ], testSchema ) await testkit.execute(testQuery, {}, { requestContext: {} }) expectContextContains({ currentUser: MOCK_USER, }) expect(mockedGetCurrentUser).toHaveBeenCalledWith( { email: '[email protected]', sub: '1' }, { schema: 'mocked-schema-bearer', token: 'mocked-undecoded-token', type: 'mocked-auth-type', }, { context: {}, event: {} } ) }) it('Does not swallow exceptions raised in getCurrentUser', async () => { const mockedGetCurrentUser = jest .fn() .mockRejectedValue(new Error('Could not fetch user from db.')) const testkit = createTestkit( [ useEngine(GraphQLJS), useRedwoodAuthContext(mockedGetCurrentUser, authDecoder), ], testSchema ) await expect(async () => { await testkit.execute(testQuery, {}, { requestContext: {} }) }).rejects.toEqual( new Error('Exception in getCurrentUser: Could not fetch user from db.') ) expect(mockedGetCurrentUser).toHaveBeenCalled() }) // @todo: Test exception raised when fetching auth context/parsing provider header })
5,521
0
petrpan-code/redwoodjs/redwood/packages/graphql-server/src/plugins
petrpan-code/redwoodjs/redwood/packages/graphql-server/src/plugins/__tests__/useRedwoodDirective.test.ts
import { useEngine } from '@envelop/core' import { assertSingleExecutionValue, createTestkit } from '@envelop/testing' import type { FieldDefinitionNode, GraphQLDirective } from 'graphql' import * as GraphQLJS from 'graphql' import { getDirectiveValues } from 'graphql' import type { Plugin } from 'graphql-yoga' import { createSchema } from 'graphql-yoga' import type { GraphQLTypeWithFields } from '../../index' import { useRedwoodDirective, DirectiveType } from '../useRedwoodDirective' // ===== Test Setup ====== const AUTH_ERROR_MESSAGE = 'Sorry, you cannot do that' const schemaWithDirectiveQueries = createSchema({ typeDefs: ` directive @requireAuth(roles: [String]) on FIELD_DEFINITION directive @skipAuth on FIELD_DEFINITION directive @truncate(maxLength: Int!, separator: String!) on FIELD_DEFINITION type Post { title: String! @skipAuth description: String! @truncate(maxLength: 5, separator: ".") } type UserProfile { name: String! @skipAuth email: String! @requireAuth } type WithoutDirectiveType { id: Int! description: String! } type Query { protected: String @requireAuth public: String @skipAuth noDirectiveSpecified: String posts: [Post!]! @skipAuth userProfiles: [UserProfile!]! @skipAuth ambiguousAuthQuery: String @requireAuth @skipAuth withoutDirective: WithoutDirectiveType @skipAuth } input CreatePostInput { title: String! } input UpdatePostInput { title: String! } type Mutation { createPost(input: CreatePostInput!): Post! @skipAuth updatePost(input: UpdatePostInput!): Post! @requireAuth deletePost(title: String!): Post! @requireAuth(roles: ["admin", "publisher"]) } `, resolvers: { Query: { protected: (_root, _args, _context) => 'protected', public: (_root, _args, _context) => 'public', noDirectiveSpecified: () => 'i should not be returned', posts: () => [ { title: 'Five ways to test Redwood directives', description: 'Read this to learn about directive testing', }, ] as Record<string, any>, userProfiles: () => [ { name: 'John Doe', email: '[email protected]', }, ], ambiguousAuthQuery: (_root, _args, _context) => 'am i allowed?', withoutDirective: (_root, _args, _context) => ({ id: 42, description: 'I am a type without any directives', }), }, Mutation: { createPost: (_root, args, _context) => { return { title: args.input.title, } }, updatePost: (_root, args, _context) => { return { title: args.input.title, } }, deletePost: (_root, _args, _context) => {}, }, }, }) const testInstance = createTestkit( [ useEngine(GraphQLJS), useRedwoodDirective({ onResolvedValue: () => { throw new Error(AUTH_ERROR_MESSAGE) }, type: DirectiveType.VALIDATOR, name: 'requireAuth', }), useRedwoodDirective({ onResolvedValue: () => { return }, type: DirectiveType.VALIDATOR, name: 'skipAuth', }), ] as Plugin[], schemaWithDirectiveQueries ) // ====== End Test Setup ====== describe('Directives on Queries', () => { it('Should disallow execution on requireAuth', async () => { const result = await testInstance.execute(`query { protected }`) assertSingleExecutionValue(result) expect(result.errors).toBeTruthy() expect(result.errors?.[0].message).toBe(AUTH_ERROR_MESSAGE) expect(result.data?.protected).toBeNull() }) it('Should allow execution on skipAuth', async () => { const result = await testInstance.execute(`query { public }`) assertSingleExecutionValue(result) expect(result.errors).toBeFalsy() expect(result.data?.public).toBe('public') }) it('Should not require Type fields (ie, not Query or Mutation root types) to have directives declared', async () => { const result = await testInstance.execute(`query { posts { title } }`) assertSingleExecutionValue(result) expect(result.errors).toBeFalsy() const posts = result.data?.posts as Record<string, any>[] expect(posts).toBeTruthy() expect(posts[0]).toHaveProperty('title') expect(posts[0].title).toEqual('Five ways to test Redwood directives') }) it('Should enforce a requireAuth() directive if a Type field declares that directive', async () => { const result = await testInstance.execute( `query { userProfiles { name, email } }` ) assertSingleExecutionValue(result) expect(result.errors).toBeTruthy() expect(result.errors?.[0].message).toBe(AUTH_ERROR_MESSAGE) expect(result.data).toBeFalsy() expect(result.data?.name).toBeUndefined() expect(result.data?.email).toBeUndefined() }) it('Should permit a skipAuth() directive if a Type field declares that directive', async () => { const result = await testInstance.execute(`query { userProfiles { name } }`) assertSingleExecutionValue(result) const userProfiles = result.data?.userProfiles as Record<string, any>[] expect(result.errors).toBeFalsy() expect(result.data).toBeTruthy() expect(userProfiles).toBeTruthy() expect(userProfiles[0]).toHaveProperty('name') expect(userProfiles[0]).not.toHaveProperty('email') expect(userProfiles[0].name).toEqual('John Doe') }) it('Should disallow execution of a Query with requireAuth() even if another directive says to skip', async () => { const result = await testInstance.execute(`query { ambiguousAuthQuery }`) assertSingleExecutionValue(result) expect(result.errors).toBeTruthy() expect(result.errors?.[0].message).toBe(AUTH_ERROR_MESSAGE) expect(result.data?.ambiguousAuthQuery).toBeNull() }) it('Should allow querying of types with no directive, as long as the query has a directive', async () => { const result = await testInstance.execute(`query { withoutDirective { id } }`) assertSingleExecutionValue(result) expect(result.errors).toBeFalsy() expect(result.data?.withoutDirective).not.toBeNull() expect(result.data?.withoutDirective).toEqual({ id: 42 }) }) }) describe('Directives on Mutations', () => { it('Should allow mutation on skipAuth', async () => { const result = await testInstance.execute( `mutation { createPost(input: { title: "Post Created" }) { title } }` ) assertSingleExecutionValue(result) expect(result.errors).toBeFalsy() expect(result.data).toBeTruthy() expect(result.data?.createPost).toBeTruthy() expect(result.data?.createPost).toHaveProperty('title') expect(result.data?.createPost).toEqual({ title: 'Post Created' }) }) it('Should disallow mutation on requireAuth', async () => { const result = await testInstance.execute( `mutation { updatePost(input: { title: "Post changed" }) { title } }` ) assertSingleExecutionValue(result) expect(result.errors).toBeTruthy() expect(result.errors?.[0].message).toBe(AUTH_ERROR_MESSAGE) expect(result.data).toBeFalsy() }) // note there is no actual roles check here it('Should disallow mutation on requireAuth() with roles given', async () => { const result = await testInstance.execute( `mutation { deletePost(title: "Post to delete") { title } }` ) assertSingleExecutionValue(result) expect(result.errors).toBeTruthy() expect(result.errors?.[0].message).toBe(AUTH_ERROR_MESSAGE) expect(result.data).toBeFalsy() }) it('Should identify the role names specified in requireAuth()', async () => { const mutationType = schemaWithDirectiveQueries.getType( 'Mutation' ) as GraphQLTypeWithFields const deletePost = mutationType.getFields()['deletePost'] //getFields()['deletePost'] const directive = schemaWithDirectiveQueries.getDirective( 'requireAuth' ) as GraphQLDirective const { roles } = getDirectiveValues( directive, deletePost.astNode as FieldDefinitionNode, { args: 'roles', } ) as { roles: string[] } expect(roles).toContain('admin') expect(roles).toContain('publisher') expect(roles).not.toContain('author') }) it('Should get the argument values for a directive', async () => { const postType = schemaWithDirectiveQueries.getType( 'Post' ) as GraphQLTypeWithFields const description = postType.getFields()['description'] const directive = schemaWithDirectiveQueries.getDirective( 'truncate' ) as GraphQLDirective const directiveArgs = getDirectiveValues( directive, description.astNode as FieldDefinitionNode ) expect(directiveArgs).toHaveProperty('maxLength') expect(directiveArgs?.maxLength).toEqual(5) expect(directiveArgs).toHaveProperty('separator') expect(directiveArgs?.separator).toEqual('.') }) it('Should get the specified argument value for a directive', async () => { const postType = schemaWithDirectiveQueries.getType( 'Post' ) as GraphQLTypeWithFields const description = postType.getFields()['description'] const directive = schemaWithDirectiveQueries.getDirective( 'truncate' ) as GraphQLDirective const { maxLength } = getDirectiveValues( directive, description.astNode as FieldDefinitionNode ) as { maxLength: number } expect(maxLength).toEqual(5) }) })
5,522
0
petrpan-code/redwoodjs/redwood/packages/graphql-server/src/plugins
petrpan-code/redwoodjs/redwood/packages/graphql-server/src/plugins/__tests__/useRedwoodError.test.ts
import type { APIGatewayProxyEvent, Context } from 'aws-lambda' import { CurrencyDefinition, CurrencyResolver } from 'graphql-scalars' import { createLogger } from '@redwoodjs/api/logger' import { createGraphQLHandler } from '../../functions/graphql' jest.mock('../../makeMergedSchema', () => { const { createGraphQLError } = require('graphql-yoga') const { makeExecutableSchema } = require('@graphql-tools/schema') const { ForbiddenError, RedwoodGraphQLError, } = require('@redwoodjs/graphql-server/dist/errors') const { EmailValidationError, RedwoodError } = require('@redwoodjs/api') const { CurrencyResolver } = require('graphql-scalars') class WeatherError extends RedwoodError { constructor(message: string, extensions?: Record<string, any>) { super(message, extensions) } } // Return executable schema return { makeMergedSchema: () => makeExecutableSchema({ typeDefs: /* GraphQL */ ` type Query { me: User! } type User { id: ID! name: String! } type Query { forbiddenUser: User! getUser(id: Int!): User! invalidUser: User! unexpectedUser: User! graphQLErrorUser: User! redwoodGraphQLErrorUser: User! } scalar Currency type Product { id: Int! name: String! currency_iso_4217: Currency! } type Query { products: [Product!]! invalidProducts: [Product!]! } type Weather { temperature: Int! } type Query { weather: Weather! } `, resolvers: { Currency: CurrencyResolver, Query: { me: () => { return { _id: 1, firstName: 'Ba', lastName: 'Zinga' } }, forbiddenUser: () => { throw new ForbiddenError('You are forbidden') }, graphQLErrorUser: () => { throw createGraphQLError('You are forbidden by a GraphQLError') }, redwoodGraphQLErrorUser: () => { throw new RedwoodGraphQLError( 'You are forbidden by a RedwoodGraphQLError' ) }, invalidUser: () => { throw new EmailValidationError('emailmissingatexample.com') }, unexpectedUser: () => { throw new Error( 'Connection to database failed at 192.168.1 port 5678' ) }, getUser: (id) => { return { id, firstName: 'Ba', lastName: 'Zinga' } }, products: () => { return [{ id: 1, name: 'Product 1', currency_iso_4217: 'USD' }] }, invalidProducts: () => { return [ { id: 2, name: 'Product 2', currency_iso_4217: 'Calamari flan', }, ] }, weather: () => { throw new WeatherError('Check outside instead', { code: 'RATE_LIMIT', }) }, }, User: { id: (u) => u._id, name: (u) => `${u.firstName} ${u.lastName}`, }, }, }), } }) jest.mock('../../directives/makeDirectives', () => { return { makeDirectivesForPlugin: () => [], } }) interface MockLambdaParams { headers?: { [key: string]: string } body?: string | null httpMethod: string [key: string]: any } const mockLambdaEvent = ({ headers, body = null, httpMethod, ...others }: MockLambdaParams): APIGatewayProxyEvent => { return { headers: headers || {}, body, httpMethod, multiValueQueryStringParameters: null, isBase64Encoded: false, multiValueHeaders: {}, // this is silly - the types require a value. It definitely can be undefined, e.g. on Vercel. path: '/graphql', pathParameters: null, stageVariables: null, queryStringParameters: null, requestContext: null as any, resource: null as any, ...others, } } describe('useRedwoodError', () => { describe('when masking errors', () => { it('returns data when there is no error', async () => { const handler = createGraphQLHandler({ loggerConfig: { logger: createLogger({}), options: {} }, sdls: {}, directives: {}, services: {}, onException: () => {}, }) const mockedEvent = mockLambdaEvent({ headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ query: '{ me { id, name } }' }), httpMethod: 'POST', }) const response = await handler(mockedEvent, {} as Context) const { data } = JSON.parse(response.body) expect(response.statusCode).toBe(200) expect(data).toEqual({ me: { id: '1', name: 'Ba Zinga' } }) }) it('returns an unmasked error message when the request is forbidden', async () => { const handler = createGraphQLHandler({ loggerConfig: { logger: createLogger({}), options: {} }, sdls: {}, directives: {}, services: {}, onException: () => {}, }) const mockedEvent = mockLambdaEvent({ headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ query: '{ forbiddenUser { id, name } }' }), httpMethod: 'POST', }) const response = await handler(mockedEvent, {} as Context) const { data, errors } = JSON.parse(response.body) expect(data).toBeNull() expect(errors[0].message).toEqual('You are forbidden') }) it('masks the error message when the request has an unexpected error', async () => { const handler = createGraphQLHandler({ loggerConfig: { logger: createLogger({}), options: {} }, sdls: {}, directives: {}, services: {}, onException: () => {}, }) const mockedEvent = mockLambdaEvent({ headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ query: '{ unexpectedUser { id, name } }' }), httpMethod: 'POST', }) const response = await handler(mockedEvent, {} as Context) const { data, errors } = JSON.parse(response.body) expect(data).toBeNull() expect(errors[0].message).toEqual('Something went wrong.') }) it('masks the error message when the request has an unexpected error with a custom message', async () => { const handler = createGraphQLHandler({ loggerConfig: { logger: createLogger({}), options: {} }, sdls: {}, directives: {}, services: {}, defaultError: 'Please try again.', onException: () => {}, }) const mockedEvent = mockLambdaEvent({ headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ query: '{ unexpectedUser { id, name } }' }), httpMethod: 'POST', }) const response = await handler(mockedEvent, {} as Context) const { data, errors } = JSON.parse(response.body) expect(data).toBeNull() expect(errors[0].message).toEqual('Please try again.') }) describe('with Service Validation errors', () => { it('Service', async () => { const handler = createGraphQLHandler({ loggerConfig: { logger: createLogger({}), options: {} }, sdls: {}, directives: {}, services: {}, onException: () => {}, }) const mockedEvent = mockLambdaEvent({ headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ query: '{ invalidUser { id, name } }' }), httpMethod: 'POST', }) const response = await handler(mockedEvent, {} as Context) const { data, errors } = JSON.parse(response.body) expect(response.statusCode).toBe(200) expect(data).toBeNull() expect(errors[0].message).toContain( 'Emailmissingatexample.com must be formatted' ) }) }) describe('with a RedwoodGraphQLError', () => { it('does not mask error message', async () => { const handler = createGraphQLHandler({ loggerConfig: { logger: createLogger({}), options: {} }, sdls: {}, directives: {}, services: {}, onException: () => {}, }) const mockedEvent = mockLambdaEvent({ headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ query: '{ redwoodGraphQLErrorUser { id, name } }', }), httpMethod: 'POST', }) const response = await handler(mockedEvent, {} as Context) const { data, errors } = JSON.parse(response.body) expect(response.statusCode).toBe(200) expect(data).toBeNull() expect(errors[0].message).toContain( 'You are forbidden by a RedwoodGraphQLError' ) }) }) describe('with a GraphQLError', () => { it('does not mask error message', async () => { const handler = createGraphQLHandler({ loggerConfig: { logger: createLogger({}), options: {} }, sdls: {}, directives: {}, services: {}, onException: () => {}, }) const mockedEvent = mockLambdaEvent({ headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ query: '{ graphQLErrorUser { id, name } }', }), httpMethod: 'POST', }) const response = await handler(mockedEvent, {} as Context) const { data, errors } = JSON.parse(response.body) expect(response.statusCode).toBe(200) expect(data).toBeNull() expect(errors[0].message).toContain( 'You are forbidden by a GraphQLError' ) }) }) describe('with Custom Scalar type errors', () => { it('returns data when there is a valid scalar currency', async () => { const handler = createGraphQLHandler({ loggerConfig: { logger: createLogger({}), options: {} }, sdls: {}, directives: {}, services: {}, schemaOptions: { typeDefs: [CurrencyDefinition], resolvers: { Currency: CurrencyResolver }, }, onException: () => {}, }) const mockedEvent = mockLambdaEvent({ headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ query: '{ products { id, name, currency_iso_4217 } }', }), httpMethod: 'POST', }) const response = await handler(mockedEvent, {} as Context) const { data, errors } = JSON.parse(response.body) expect(errors).toBeUndefined() expect(data.products[0].currency_iso_4217).toEqual('USD') }) it('masks a custom scalar currency type runtime validation error message', async () => { const handler = createGraphQLHandler({ loggerConfig: { logger: createLogger({}), options: {} }, sdls: {}, directives: {}, services: {}, schemaOptions: { typeDefs: [CurrencyDefinition], resolvers: { Currency: CurrencyResolver }, }, onException: () => {}, }) const mockedEvent = mockLambdaEvent({ headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ query: '{ invalidProducts { id, name, currency_iso_4217 } }', }), httpMethod: 'POST', }) const response = await handler(mockedEvent, {} as Context) const { data, errors } = JSON.parse(response.body) expect(data).toBeNull() expect(errors[0].message).toEqual('Something went wrong.') }) }) describe('with Custom Redwood Error', () => { it('shows the custom error message', async () => { const handler = createGraphQLHandler({ loggerConfig: { logger: createLogger({}), options: {} }, sdls: {}, directives: {}, services: {}, onException: () => {}, }) const mockedEvent = mockLambdaEvent({ headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ query: '{ weather { temperature } }', }), httpMethod: 'POST', }) const response = await handler(mockedEvent, {} as Context) const { data, errors } = JSON.parse(response.body) expect(data).toBeNull() expect(errors[0].message).toEqual('Check outside instead') }) }) }) })
5,523
0
petrpan-code/redwoodjs/redwood/packages/graphql-server/src/plugins
petrpan-code/redwoodjs/redwood/packages/graphql-server/src/plugins/__tests__/useRedwoodGlobalContextSetter.test.ts
import { useEngine } from '@envelop/core' import { createTestkit } from '@envelop/testing' import * as GraphQLJS from 'graphql' import type { GlobalContext } from '../../index' import { context, getAsyncStoreInstance, setContext } from '../../index' import { testSchema, testQuery } from '../__fixtures__/common' import { useRedwoodGlobalContextSetter } from '../useRedwoodGlobalContextSetter' import { useRedwoodPopulateContext } from '../useRedwoodPopulateContext' test('Context is correctly populated', async () => { const testkit = createTestkit( [ useEngine(GraphQLJS), useRedwoodPopulateContext(() => ({ hello: 'world' })), useRedwoodPopulateContext({ foo: 'bar' }), useRedwoodGlobalContextSetter(), ], testSchema ) await getAsyncStoreInstance().run( new Map<string, GlobalContext>(), async () => { await testkit.execute(testQuery, {}, {}) expect(context.hello).toBe('world') expect(context.foo).toBe('bar') expect(context.bazinga).toBeUndefined() } ) }) test('Plugin lets you populate context at any point in the lifecycle', async () => { const testkit = createTestkit( [ useEngine(GraphQLJS), useRedwoodGlobalContextSetter(), useRedwoodPopulateContext(() => ({ hello: 'world' })), useRedwoodPopulateContext({ foo: 'bar' }), useRedwoodPopulateContext({ bazinga: 'new value!' }), ], testSchema ) await getAsyncStoreInstance().run( new Map<string, GlobalContext>(), async () => { await testkit.execute(testQuery, {}, {}) expect(context.hello).toBe('world') expect(context.foo).toBe('bar') expect(context.bazinga).toBe('new value!') } ) }) test('setContext erases the existing context', async () => { const testkit = createTestkit( [ useEngine(GraphQLJS), useRedwoodPopulateContext(() => ({ hello: 'world' })), useRedwoodPopulateContext({ foo: 'bar' }), useRedwoodGlobalContextSetter(), ], testSchema ) await getAsyncStoreInstance().run( new Map<string, GlobalContext>(), async () => { await testkit.execute(testQuery, {}, {}) setContext({ bazinga: 'new value!' }) expect(context.hello).toBeUndefined() expect(context.foo).toBeUndefined() expect(context.bazinga).toBe('new value!') } ) })
5,524
0
petrpan-code/redwoodjs/redwood/packages/graphql-server/src/plugins
petrpan-code/redwoodjs/redwood/packages/graphql-server/src/plugins/__tests__/useRedwoodLogger.test.ts
import { existsSync, readFileSync, statSync } from 'fs' import os from 'os' import { join } from 'path' import { useEngine } from '@envelop/core' import { createTestkit } from '@envelop/testing' import * as GraphQLJS from 'graphql' import type { Logger, LoggerOptions } from '@redwoodjs/api/logger' import { createLogger } from '@redwoodjs/api/logger' import { testSchema, testQuery, testErrorQuery, testParseErrorQuery, testFilteredQuery, testValidationErrorQuery, } from '../__fixtures__/common' import type { LoggerConfig } from '../useRedwoodLogger' import { useRedwoodLogger } from '../useRedwoodLogger' const watchFileCreated = (filename) => { return new Promise((resolve, reject) => { const TIMEOUT = 800 const INTERVAL = 100 const threshold = TIMEOUT / INTERVAL let counter = 0 const interval = setInterval(() => { // On some CI runs file is created but not filled if (existsSync(filename) && statSync(filename).size !== 0) { clearInterval(interval) resolve(null) } else if (counter <= threshold) { counter++ } else { clearInterval(interval) reject(new Error(`${filename} was not created.`)) } }, INTERVAL) }) } const parseLogFile = (logFile) => { const parsedLogFile = JSON.parse( `[${readFileSync(logFile) .toString() .trim() .split(/\r\n|\n/) .join(',')}]` ) return parsedLogFile } const setupLogger = ( loggerOptions: LoggerOptions, destination: string ): { logger: Logger } => { const logger = createLogger({ options: { ...loggerOptions }, destination: destination, }) return { logger } } describe('Populates context', () => { const logFile = join( os.tmpdir(), '_' + Math.random().toString(36).substr(2, 9) ) const { logger } = setupLogger({ level: 'trace' }, logFile) it('Should log debug statements around GraphQL the execution phase', async () => { const loggerConfig = { logger, options: { data: true, query: true, operationName: true }, } as LoggerConfig const testkit = createTestkit( [useEngine(GraphQLJS), useRedwoodLogger(loggerConfig)], testSchema ) await testkit.execute(testQuery, {}, {}) await watchFileCreated(logFile) const logStatements = parseLogFile(logFile) const executionCompleted = logStatements.pop() const executionStarted = logStatements.pop() expect(executionStarted).toHaveProperty('level') expect(executionStarted).toHaveProperty('time') expect(executionStarted).toHaveProperty('msg') expect(executionStarted).toHaveProperty('query') expect(executionStarted.name).toEqual('graphql-server') expect(executionStarted.level).toEqual(20) expect(executionStarted.msg).toEqual('GraphQL execution started: meQuery') expect(executionCompleted).toHaveProperty('level') expect(executionCompleted).toHaveProperty('time') expect(executionCompleted).toHaveProperty('msg') expect(executionCompleted).toHaveProperty('query') expect(executionCompleted).toHaveProperty('operationName') expect(executionCompleted).toHaveProperty('data') expect(executionCompleted.msg).toEqual( 'GraphQL execution completed: meQuery' ) expect(executionCompleted.data).toHaveProperty('me') expect(executionCompleted.operationName).toEqual('meQuery') expect(executionCompleted.data.me.name).toEqual('Ba Zinga') }) it('Should log an error when GraphQL the parsing phase fails', async () => { const loggerConfig = { logger, options: { data: true, query: true, operationName: true }, } as LoggerConfig const testkit = createTestkit( [useEngine(GraphQLJS), useRedwoodLogger(loggerConfig)], testSchema ) await testkit.execute(testParseErrorQuery, {}, {}) await watchFileCreated(logFile) const logStatements = parseLogFile(logFile) const lastStatement = logStatements.pop() expect(lastStatement.level).toEqual(50) expect(lastStatement).toHaveProperty('level') expect(lastStatement).toHaveProperty('time') expect(lastStatement).toHaveProperty('msg') expect(lastStatement.name).toEqual('graphql-server') expect(lastStatement.msg).toEqual( 'Cannot query field "unknown_field" on type "User".' ) }) it('Should log an error when the GraphQL validation phase fails', async () => { const loggerConfig = { logger, options: { data: true, query: true, operationName: true }, } as LoggerConfig const testkit = createTestkit( [useEngine(GraphQLJS), useRedwoodLogger(loggerConfig)], testSchema ) await testkit.execute(testValidationErrorQuery, {}, {}) await watchFileCreated(logFile) const logStatements = parseLogFile(logFile) const lastStatement = logStatements.pop() expect(lastStatement.level).toEqual(50) expect(lastStatement).toHaveProperty('level') expect(lastStatement.name).toEqual('graphql-server') expect(lastStatement).toHaveProperty('time') expect(lastStatement).toHaveProperty('msg') expect(lastStatement.msg).toEqual( 'Syntax Error: Expected "$", found Name "id".' ) expect(lastStatement).toHaveProperty('err') expect(lastStatement.err).toHaveProperty('type') expect(lastStatement.err.type).toEqual('GraphQLError') expect(lastStatement.err.message).toEqual( 'Syntax Error: Expected "$", found Name "id".' ) }) it('Should log an error when the resolver raises an exception', async () => { const loggerConfig = { logger, options: {}, } as LoggerConfig const testkit = createTestkit( [useEngine(GraphQLJS), useRedwoodLogger(loggerConfig)], testSchema ) await testkit.execute(testErrorQuery, {}, {}) await watchFileCreated(logFile) const logStatements = parseLogFile(logFile) const errorLogStatement = logStatements.pop() expect(errorLogStatement).toHaveProperty('level') expect(errorLogStatement).toHaveProperty('time') expect(errorLogStatement).toHaveProperty('msg') expect(errorLogStatement).toHaveProperty('err') expect(errorLogStatement.name).toEqual('graphql-server') expect(errorLogStatement.level).toEqual(50) expect(errorLogStatement.msg).toEqual('You are forbidden') }) it('Should log an error with type and stack trace info when the resolver raises an exception', async () => { const loggerConfig = { logger, options: {}, } as LoggerConfig const testkit = createTestkit( [useEngine(GraphQLJS), useRedwoodLogger(loggerConfig)], testSchema ) await testkit.execute(testErrorQuery, {}, {}) await watchFileCreated(logFile) const logStatements = parseLogFile(logFile) const errorLogStatement = logStatements.pop() expect(errorLogStatement).toHaveProperty('err') expect(errorLogStatement.err).toHaveProperty('stack') expect(errorLogStatement.err.type).toEqual('GraphQLError') expect(errorLogStatement.err.path).toContain('forbiddenUser') expect(errorLogStatement.err.message).toEqual('You are forbidden') }) it('Should not log filtered graphql operations', async () => { const loggerConfig = { logger, options: { excludeOperations: ['FilteredQuery'], }, } as LoggerConfig const testkit = createTestkit( [useEngine(GraphQLJS), useRedwoodLogger(loggerConfig)], testSchema ) await testkit.execute(testFilteredQuery, {}, {}) await watchFileCreated(logFile) const logStatements = parseLogFile(logFile) expect(logStatements).not.toEqual( expect.arrayContaining([ expect.objectContaining({ msg: expect.stringContaining('FilteredQuery'), }), ]) ) }) })
5,525
0
petrpan-code/redwoodjs/redwood/packages/graphql-server/src/plugins
petrpan-code/redwoodjs/redwood/packages/graphql-server/src/plugins/__tests__/useRedwoodPopulateContext.test.ts
import { useEngine } from '@envelop/core' import { createSpiedPlugin, createTestkit } from '@envelop/testing' import * as GraphQLJS from 'graphql' import { testSchema, testQuery } from '../__fixtures__/common' import { useRedwoodPopulateContext } from '../useRedwoodPopulateContext' describe('Populates context', () => { const spiedPlugin = createSpiedPlugin() const expectContextContains = (obj) => { expect(spiedPlugin.spies.beforeContextBuilding).toHaveBeenCalledWith( expect.objectContaining({ context: expect.objectContaining(obj), }) ) } beforeEach(() => { spiedPlugin.reset() }) it('Should extend context based on output of function', async () => { const populateContextSpy = jest.fn(() => { return { bazinga: true, } }) const testkit = createTestkit( [ useEngine(GraphQLJS), useRedwoodPopulateContext(populateContextSpy), // @NOTE add spy here to check if context has been changed spiedPlugin.plugin, ], testSchema ) await testkit.execute(testQuery, {}, {}) expect(populateContextSpy).toHaveBeenCalled() expectContextContains({ bazinga: true }) }) it('Should extend context with an object, if one is provided', async () => { const populateContextSpy = jest.fn(() => { return { bazinga: true, } }) const testkit = createTestkit( [ useEngine(GraphQLJS), useRedwoodPopulateContext({ dtWasHere: 'hello!', }), // @NOTE add spy here to check if context has been changed spiedPlugin.plugin, ], testSchema ) await testkit.execute(testQuery, {}, {}) expect(populateContextSpy).not.toHaveBeenCalled() expectContextContains({ dtWasHere: 'hello!' }) }) })
5,545
0
petrpan-code/redwoodjs/redwood/packages/internal/src
petrpan-code/redwoodjs/redwood/packages/internal/src/__tests__/ast.test.ts
import path from 'path' import { getGqlQueries, getNamedExports, hasDefaultExport, getCellGqlQuery, fileToAst, } from '../ast' jest.mock('@redwoodjs/project-config', () => { const path = require('path') const baseFixturePath = path.join(__dirname, 'fixtures') return { getPaths: () => ({ base: baseFixturePath, web: { src: path.join(baseFixturePath, 'web/src'), base: path.join(baseFixturePath, 'web'), }, api: { src: path.join(baseFixturePath, 'api/src'), base: path.join(baseFixturePath, 'api'), }, }), } }) const getFixturePath = (relativeFilePath: string) => { return path.join(__dirname, `fixtures/${relativeFilePath}`) } test('extracts named exports', () => { // Fixture is in web folder, because it has a JSX export const fakeCode = fileToAst(getFixturePath('/web/src/exports.ts')) const n = getNamedExports(fakeCode) expect(n).toMatchInlineSnapshot(` [ { "location": { "column": 9, "line": 1, }, "name": "exportA", "type": "re-export", }, { "location": { "column": 18, "line": 1, }, "name": "exportB", "type": "re-export", }, { "location": { "column": 13, "line": 3, }, "name": "myVariableExport", "type": "variable", }, { "location": { "column": 13, "line": 5, }, "name": "myArrowFunctionExport", "type": "variable", }, { "location": { "column": 16, "line": 9, }, "name": "myFunctionExport", "type": "function", }, { "location": { "column": 13, "line": 11, }, "name": "MyClassExport", "type": "class", }, ] `) }) test('tests default exports', () => { expect( hasDefaultExport(fileToAst(getFixturePath('/defaultExports/multiLine.js'))) ).toEqual(true) expect( hasDefaultExport(fileToAst(getFixturePath('defaultExports/singleLine.js'))) ).toEqual(true) expect( hasDefaultExport(fileToAst(getFixturePath('defaultExports/none.js'))) ).toEqual(false) }) test('Returns the exported query from a cell (ignoring others)', () => { const cellFileAst = fileToAst(getFixturePath('web/src/cell.tsx')) const cellQuery = getCellGqlQuery(cellFileAst) expect(cellQuery).toMatchInlineSnapshot(` " query BazingaQuery($id: String!) { member: member(id: $id) { id } } " `) }) test('Returns the all queries from a file using getGqlQueries', () => { const cellFileAst = fileToAst(getFixturePath('web/src/cell.tsx')) const cellQuery = getGqlQueries(cellFileAst) expect(cellQuery).toMatchInlineSnapshot(` [ " query BazingaQuery($id: String!) { member: member(id: $id) { id } } ", " query FindSoftKitten($id: String!) { softKitten: softKitten(id: $id) { id } } ", "query JustForFun { itsFriday {} }", ] `) }) test('Handles typecast syntax without erroring', () => { expect(() => fileToAst(getFixturePath('api/typecast.ts'))).not.toThrow() })
5,546
0
petrpan-code/redwoodjs/redwood/packages/internal/src
petrpan-code/redwoodjs/redwood/packages/internal/src/__tests__/build_api.test.ts
import fs from 'fs' import path from 'path' import * as babel from '@babel/core' import { getApiSideBabelPlugins, getApiSideDefaultBabelConfig, } from '@redwoodjs/babel-config' import { ensurePosixPath, getPaths } from '@redwoodjs/project-config' import { cleanApiBuild, prebuildApiFiles } from '../build/api' import { findApiFiles } from '../files' const FIXTURE_PATH = path.resolve( __dirname, '../../../../__fixtures__/example-todo-main' ) const cleanPaths = (p) => { return ensurePosixPath(path.relative(FIXTURE_PATH, p)) } // Fixtures, filled in beforeAll let prebuiltFiles let relativePaths beforeAll(() => { process.env.RWJS_CWD = FIXTURE_PATH cleanApiBuild() const apiFiles = findApiFiles() prebuiltFiles = prebuildApiFiles(apiFiles) relativePaths = prebuiltFiles .filter((x) => typeof x !== 'undefined') .map(cleanPaths) }) afterAll(() => { delete process.env.RWJS_CWD }) test('api files are prebuilt', () => { // Builds non-nested functions expect(relativePaths).toContain( '.redwood/prebuild/api/src/functions/graphql.js' ) // Builds graphql folder expect(relativePaths).toContain( '.redwood/prebuild/api/src/graphql/todos.sdl.js' ) // Builds nested function expect(relativePaths).toContain( '.redwood/prebuild/api/src/functions/nested/nested.js' ) }) test('api prebuild uses babel config only from the api side root', () => { const p = prebuiltFiles.filter((p) => p.endsWith('dog.js')).pop() const code = fs.readFileSync(p, 'utf-8') expect(code).toContain(`import dog from "dog-bless";`) // Should ignore root babel config expect(code).not.toContain(`import kitty from "kitty-purr"`) }) // Still a bit of a mystery why this plugin isn't transforming gql tags test.skip('api prebuild transforms gql with `babel-plugin-graphql-tag`', () => { // babel-plugin-graphql-tag should transpile the "gql" parts of our files, // achieving the following: // 1. removing the `graphql-tag` import // 2. convert the gql syntax into graphql's ast. // // https://www.npmjs.com/package/babel-plugin-graphql-tag const builtFiles = prebuildApiFiles(findApiFiles()) const p = builtFiles .filter((x) => typeof x !== 'undefined') .filter((p) => p.endsWith('todos.sdl.js')) .pop() const code = fs.readFileSync(p, 'utf-8') expect(code.includes('import gql from "graphql-tag";')).toEqual(false) expect(code.includes('gql`')).toEqual(false) }) test('jest mock statements also handle', () => { const pathToTest = path.join(getPaths().api.services, 'todos/todos.test.js') const code = fs.readFileSync(pathToTest, 'utf-8') const defaultOptions = getApiSideDefaultBabelConfig() // Step 1: prebuild service/todos.test.js const outputForJest = babel.transform(code, { ...defaultOptions, filename: pathToTest, cwd: getPaths().api.base, // We override the plugins, to match packages/testing/config/jest/api/index.js plugins: getApiSideBabelPlugins({ forJest: true }), }).code // Step 2: check that output has correct import statement path expect(outputForJest).toContain('import dog from "../../lib/dog"') // Step 3: check that output has correct jest.mock path expect(outputForJest).toContain('jest.mock("../../lib/dog"') })
5,547
0
petrpan-code/redwoodjs/redwood/packages/internal/src
petrpan-code/redwoodjs/redwood/packages/internal/src/__tests__/build_web.test.ts
import path from 'path' import { prebuildWebFile } from '@redwoodjs/babel-config' import { ensurePosixPath, getPaths } from '@redwoodjs/project-config' import { prebuildWebFiles, cleanWebBuild } from '../build/web' import { findWebFiles } from '../files' const FIXTURE_PATH = path.resolve( __dirname, '../../../../__fixtures__/example-todo-main' ) const cleanPaths = (p) => { return ensurePosixPath(path.relative(FIXTURE_PATH, p)) } beforeEach(() => { process.env.RWJS_CWD = FIXTURE_PATH cleanWebBuild() }) afterAll(() => { delete process.env.RWJS_CWD }) test('web files are prebuilt (no prerender)', async () => { const webFiles = findWebFiles() const prebuiltFiles = prebuildWebFiles(webFiles) const relativePaths = prebuiltFiles .filter((x) => typeof x !== 'undefined') .map(cleanPaths) // Builds non-nested functions expect(relativePaths).toMatchInlineSnapshot(` [ ".redwood/prebuild/web/src/App.js", ".redwood/prebuild/web/src/Routes.js", ".redwood/prebuild/web/src/graphql/fragment-masking.js", ".redwood/prebuild/web/src/graphql/gql.js", ".redwood/prebuild/web/src/graphql/graphql.js", ".redwood/prebuild/web/src/graphql/index.js", ".redwood/prebuild/web/src/components/AddTodo/AddTodo.js", ".redwood/prebuild/web/src/components/AddTodoControl/AddTodoControl.js", ".redwood/prebuild/web/src/components/Check/Check.js", ".redwood/prebuild/web/src/components/NumTodosCell/NumTodosCell.js", ".redwood/prebuild/web/src/components/NumTodosTwoCell/NumTodosTwoCell.js", ".redwood/prebuild/web/src/components/TableCell/TableCell.js", ".redwood/prebuild/web/src/components/TodoItem/TodoItem.js", ".redwood/prebuild/web/src/components/TodoListCell/TodoListCell.tsx", ".redwood/prebuild/web/src/layouts/SetLayout/SetLayout.js", ".redwood/prebuild/web/src/pages/BarPage/BarPage.tsx", ".redwood/prebuild/web/src/pages/FatalErrorPage/FatalErrorPage.js", ".redwood/prebuild/web/src/pages/FooPage/FooPage.tsx", ".redwood/prebuild/web/src/pages/HomePage/HomePage.tsx", ".redwood/prebuild/web/src/pages/NotFoundPage/NotFoundPage.js", ".redwood/prebuild/web/src/pages/PrivatePage/PrivatePage.tsx", ".redwood/prebuild/web/src/pages/TypeScriptPage/TypeScriptPage.tsx", ".redwood/prebuild/web/src/pages/admin/EditUserPage/EditUserPage.jsx", ] `) }) test('Check routes are imported with require when staticImports flag is enabled', () => { const routesFile = getPaths().web.routes const prerendered = prebuildWebFile(routesFile, { prerender: true, forJest: true, })?.code /* Check that imports have the form `const HomePage = { name: "HomePage", loader: () => require("` πŸ‘ˆ Uses a require statement */ expect(prerendered).toContain(`const HomePage = {`) expect(prerendered).toContain(`const BarPage = {`) /* πŸ‘‡ Foo page is an explicitly imported page in the source const FooPage = { name: "FooPage", loader: () => require( */ expect(prerendered).toContain(`const FooPage = {`) expect(prerendered).not.toContain( `var _FooPage = _interopRequireDefault(require(` ) }) test('Check routes are imported with "import" when staticImports flag is NOT passed', () => { const routesFile = getPaths().web.routes const withoutStaticImports = prebuildWebFile(routesFile, { forJest: true, })?.code /* Check that imports have the form `const HomePage = { name: "HomePage", loader: () => import("` πŸ‘ˆ Uses an (async) import statement */ expect(withoutStaticImports).toContain(`const HomePage = {`) expect(withoutStaticImports).toContain(`const BarPage = {`) /* πŸ‘‡ Foo page is an explicitly imported page, so it should var _FooPage = _interopRequireDefault(require(\\"./pages/FooPage/FooPage\\")) (inverse of the static imports one) . . . page: _FooPage[\\"default\\"], */ expect(withoutStaticImports).not.toContain(`const FooPage = {`) expect(withoutStaticImports).toContain( `var _FooPage = _interopRequireDefault(require(` ) })
5,548
0
petrpan-code/redwoodjs/redwood/packages/internal/src
petrpan-code/redwoodjs/redwood/packages/internal/src/__tests__/clientPreset.test.ts
import path from 'path' import { generateClientPreset } from '../generate/clientPreset' import { generateGraphQLSchema } from '../generate/graphqlSchema' let shouldGenerateTrustedDocuments = false const mockTrustedDocumentsConfig = () => { return shouldGenerateTrustedDocuments } jest.mock('@redwoodjs/project-config', () => { const projectConfig = jest.requireActual('@redwoodjs/project-config') return { ...projectConfig, getConfig: () => { return { graphql: { trustedDocuments: mockTrustedDocumentsConfig() } } }, } }) beforeEach(() => { const FIXTURE_PATH = path.resolve( __dirname, '../../../../__fixtures__/example-todo-main' ) process.env.RWJS_CWD = FIXTURE_PATH }) afterEach(() => { delete process.env.RWJS_CWD jest.restoreAllMocks() }) describe('Generate client preset', () => { test('for web side', async () => { shouldGenerateTrustedDocuments = true await generateGraphQLSchema() const { clientPresetFiles } = await generateClientPreset() expect(clientPresetFiles).toHaveLength(6) const expectedEndings = [ '/fragment-masking.ts', '/index.ts', '/gql.ts', '/graphql.ts', '/persisted-documents.json', '/types.d.ts', ] const foundEndings = expectedEndings.filter((expectedEnding) => clientPresetFiles.some((filename) => filename.endsWith(expectedEnding)) ) expect(foundEndings).toHaveLength(expectedEndings.length) }) test('for api side', async () => { shouldGenerateTrustedDocuments = true await generateGraphQLSchema() const { trustedDocumentsStoreFile } = await generateClientPreset() expect(trustedDocumentsStoreFile).toContain('trustedDocumentsStore.ts') }) })
5,549
0
petrpan-code/redwoodjs/redwood/packages/internal/src
petrpan-code/redwoodjs/redwood/packages/internal/src/__tests__/configPath.test.ts
import path from 'path' import { getConfigPath } from '@redwoodjs/project-config' describe('getConfigPath', () => { it('throws an error when not in a project', () => { expect(getConfigPath).toThrowErrorMatchingInlineSnapshot( `"Could not find a "redwood.toml" file, are you sure you're in a Redwood project?"` ) }) describe('using RWJS_CWD environment variable', () => { const RWJS_CWD = process.env.RWJS_CWD const FIXTURE_BASEDIR = path.join( __dirname, '..', '..', '..', '..', '__fixtures__', 'test-project' ) afterAll(() => { process.env.RWJS_CWD = RWJS_CWD }) it('finds the correct config path when at base directory', () => { process.env.RWJS_CWD = FIXTURE_BASEDIR expect(getConfigPath()).toBe(path.join(FIXTURE_BASEDIR, 'redwood.toml')) }) it('finds the correct config path when inside a project directory', () => { process.env.RWJS_CWD = path.join( FIXTURE_BASEDIR, 'web', 'src', 'pages', 'AboutPage' ) expect(getConfigPath()).toBe(path.join(FIXTURE_BASEDIR, 'redwood.toml')) }) }) describe('using cwd', () => { const RWJS_CWD = process.env.RWJS_CWD const FIXTURE_BASEDIR = path.join( __dirname, '..', '..', '..', '..', '__fixtures__', 'test-project' ) beforeAll(() => { delete process.env.RWJS_CWD }) afterAll(() => { process.env.RWJS_CWD = RWJS_CWD jest.restoreAllMocks() }) it('finds the correct config path when at base directory', () => { const spy = jest.spyOn(process, 'cwd') spy.mockReturnValue(FIXTURE_BASEDIR) expect(getConfigPath()).toBe(path.join(FIXTURE_BASEDIR, 'redwood.toml')) }) it('finds the correct config path when inside a project directory', () => { const spy = jest.spyOn(process, 'cwd') spy.mockReturnValue( path.join(FIXTURE_BASEDIR, 'web', 'src', 'pages', 'AboutPage') ) expect(getConfigPath()).toBe(path.join(FIXTURE_BASEDIR, 'redwood.toml')) }) }) })
5,550
0
petrpan-code/redwoodjs/redwood/packages/internal/src
petrpan-code/redwoodjs/redwood/packages/internal/src/__tests__/files.test.ts
import path from 'path' const FIXTURE_PATH = path.resolve( __dirname, '../../../../__fixtures__/example-todo-main' ) beforeAll(() => { process.env.RWJS_CWD = FIXTURE_PATH }) afterAll(() => { delete process.env.RWJS_CWD }) import { ensurePosixPath, getPaths } from '@redwoodjs/project-config' import { findApiServerFunctions, findCells, findDirectoryNamedModules, findGraphQLSchemas, findPages, isCellFile, isFileInsideFolder, } from '../files' const cleanPaths = (p) => { return ensurePosixPath(path.relative(FIXTURE_PATH, p)) } test('finds all the cells', () => { const paths = findCells() const p = paths.map(cleanPaths) expect(p).toMatchInlineSnapshot(` [ "web/src/components/NumTodosCell/NumTodosCell.js", "web/src/components/NumTodosTwoCell/NumTodosTwoCell.js", "web/src/components/TodoListCell/TodoListCell.tsx", ] `) }) test('finds directory named modules', () => { const paths = findDirectoryNamedModules() const p = paths.map(cleanPaths) expect(p).toMatchInlineSnapshot(` [ "web/src/graphql/graphql.ts", "api/src/directives/requireAuth/requireAuth.js", "api/src/directives/skipAuth/skipAuth.js", "api/src/functions/healthz/healthz.js", "api/src/functions/nested/nested.ts", "api/src/services/todos/todos.js", "web/src/components/AddTodo/AddTodo.js", "web/src/components/AddTodoControl/AddTodoControl.js", "web/src/components/Check/Check.js", "web/src/components/TableCell/TableCell.js", "web/src/components/TodoItem/TodoItem.js", "web/src/layouts/SetLayout/SetLayout.js", "web/src/pages/BarPage/BarPage.tsx", "web/src/pages/FatalErrorPage/FatalErrorPage.js", "web/src/pages/FooPage/FooPage.tsx", "web/src/pages/HomePage/HomePage.tsx", "web/src/pages/NotFoundPage/NotFoundPage.js", "web/src/pages/PrivatePage/PrivatePage.tsx", "web/src/pages/TypeScriptPage/TypeScriptPage.tsx", "web/src/pages/admin/EditUserPage/EditUserPage.jsx", ] `) }) test('finds all the page files', () => { const paths = findPages() const p = paths.map(cleanPaths) expect(p).toMatchInlineSnapshot(` [ "web/src/pages/BarPage/BarPage.tsx", "web/src/pages/FatalErrorPage/FatalErrorPage.js", "web/src/pages/FooPage/FooPage.tsx", "web/src/pages/HomePage/HomePage.tsx", "web/src/pages/NotFoundPage/NotFoundPage.js", "web/src/pages/PrivatePage/PrivatePage.tsx", "web/src/pages/TypeScriptPage/TypeScriptPage.tsx", "web/src/pages/admin/EditUserPage/EditUserPage.jsx", ] `) }) test('find the graphql schema files', () => { const paths = findGraphQLSchemas() const p = paths.map(cleanPaths) expect(p[0]).toMatchInlineSnapshot(`"api/src/graphql/currentUser.sdl.ts"`) expect(p[1]).toMatchInlineSnapshot(`"api/src/graphql/todos.sdl.js"`) }) test('find api functions', () => { const paths = findApiServerFunctions() const p = paths.map(cleanPaths) expect(p).toMatchInlineSnapshot(` [ "api/src/functions/graphql.js", "api/src/functions/healthz/healthz.js", "api/src/functions/nested/nested.ts", "api/src/functions/x/index.js", ] `) }) test('isFileInsideFolder works correctly (esp on windows)', () => { expect( isFileInsideFolder( path.join(FIXTURE_PATH, 'web/src/components/TableCell/TableCell.js'), getPaths().web.base ) ).toBe(true) expect( isFileInsideFolder( path.join(FIXTURE_PATH, 'web/src/pages/NotFoundPage/NotFoundPage.js'), getPaths().web.pages ) ).toBe(true) expect( isFileInsideFolder( path.join(FIXTURE_PATH, 'web/src/pages/NotFoundPage/NotFoundPage.js'), getPaths().api.base ) ).toBe(false) expect( isFileInsideFolder( path.join(FIXTURE_PATH, 'api/src/functions/healthz/healthz.js'), getPaths().api.functions ) ).toBe(true) }) test('isCellFile detects cells correctly', () => { const invalidCell = isCellFile( path.join(FIXTURE_PATH, 'web/src/components/TableCell/TableCell.js') ) const validCell = isCellFile( path.join(FIXTURE_PATH, 'web/src/components/TodoListCell/TodoListCell.tsx') ) const notACell = isCellFile( path.join(FIXTURE_PATH, 'api/src/services/todos/DoesNotExist.js') ) expect(invalidCell).toBe(false) expect(validCell).toBe(true) expect(notACell).toBe(false) })
5,551
0
petrpan-code/redwoodjs/redwood/packages/internal/src
petrpan-code/redwoodjs/redwood/packages/internal/src/__tests__/gql.test.ts
import path from 'path' import gql from 'graphql-tag' import { listQueryTypeFieldsInProject, parseDocumentAST } from '../gql' test('parses a document AST', () => { const QUERY = gql` query POSTS { posts { id title body createdAt } numberOfPosts } ` expect(parseDocumentAST(QUERY)).toMatchInlineSnapshot(` [ { "fields": [ { "posts": [ "id", "title", "body", "createdAt", ], }, "numberOfPosts", ], "name": "POSTS", "operation": "query", }, ] `) }) test('handles inline fragments', () => { const QUERY = gql` query MyCellQuery { something { ... on SomeType { __typename } ... on SomeOtherType { __typename } } } ` expect(parseDocumentAST(QUERY)).toMatchInlineSnapshot(` [ { "fields": [ { "something": [ "__typename", "__typename", ], }, ], "name": "MyCellQuery", "operation": "query", }, ] `) }) test('handles fragments', () => { const QUERY = gql` fragment ABC on B { a } query MyCellQuery { something { ...ABC } } ` expect(parseDocumentAST(QUERY)).toMatchInlineSnapshot(` [ { "fields": [ { "something": [], }, ], "name": "MyCellQuery", "operation": "query", }, ] `) }) test('listQueryTypeFieldsInProject', async () => { const FIXTURE_PATH = path.resolve( __dirname, '../../../../__fixtures__/example-todo-main' ) // Set fixture path so it reads the sdls from example-todo-main process.env.RWJS_CWD = FIXTURE_PATH // Reimport, because rwjs/internal already calculates the paths const result = await listQueryTypeFieldsInProject() expect(result).toContain('redwood') expect(result).toContain('currentUser') expect(result).toContain('todos') expect(result).toContain('todosCount') // Restore RWJS config delete process.env.RWJS_CWD })
5,552
0
petrpan-code/redwoodjs/redwood/packages/internal/src
petrpan-code/redwoodjs/redwood/packages/internal/src/__tests__/graphqlCodeGen.test.ts
import fs from 'fs' import path from 'path' import { generateTypeDefGraphQLApi, generateTypeDefGraphQLWeb, } from '../generate/graphqlCodeGen' import { generateGraphQLSchema } from '../generate/graphqlSchema' const FIXTURE_PATH = path.resolve( __dirname, '../../../../__fixtures__/example-todo-main' ) beforeAll(() => { process.env.RWJS_CWD = FIXTURE_PATH }) afterAll(() => { delete process.env.RWJS_CWD }) afterEach(() => { jest.restoreAllMocks() }) jest.mock('@prisma/client', () => { return { ModelName: { PrismaModelOne: 'PrismaModelOne', PrismaModelTwo: 'PrismaModelTwo', Post: 'Post', Todo: 'Todo', }, } }) test('Generate gql typedefs web', async () => { await generateGraphQLSchema() jest .spyOn(fs, 'writeFileSync') .mockImplementation( (file: fs.PathOrFileDescriptor, data: string | ArrayBufferView) => { expect(file).toMatch(path.join('web', 'types', 'graphql.d.ts')) expect(data).toMatchSnapshot() } ) const { typeDefFiles } = await generateTypeDefGraphQLWeb() expect(typeDefFiles).toHaveLength(1) expect(typeDefFiles[0]).toMatch(path.join('web', 'types', 'graphql.d.ts')) }) test('Generate gql typedefs api', async () => { await generateGraphQLSchema() let codegenOutput: { file: fs.PathOrFileDescriptor data: string | ArrayBufferView } = { file: '', data: '' } jest .spyOn(fs, 'writeFileSync') .mockImplementation( (file: fs.PathOrFileDescriptor, data: string | ArrayBufferView) => { codegenOutput = { file, data } } ) const { typeDefFiles } = await generateTypeDefGraphQLApi() expect(typeDefFiles).toHaveLength(1) expect(typeDefFiles[0]).toMatch(path.join('api', 'types', 'graphql.d.ts')) const { file, data } = codegenOutput expect(file).toMatch(path.join('api', 'types', 'graphql.d.ts')) // Catchall to prevent unexpected changes to the generated file expect(data).toMatchSnapshot() // Check that JSON types are imported from prisma expect(data).toContain('JSON: Prisma.JsonValue;') expect(data).toContain('JSONObject: Prisma.JsonObject;') // Check that prisma model imports are added to the top of the file expect(data).toContain( "import { PrismaModelOne as PrismaPrismaModelOne, PrismaModelTwo as PrismaPrismaModelTwo, Post as PrismaPost, Todo as PrismaTodo } from '@prisma/client'" ) // Check printMappedModelsPlugin works correctly expect(data).toContain( `type MaybeOrArrayOfMaybe<T> = T | Maybe<T> | Maybe<T>[]` ) // Should only contain the SDL models that are also in Prisma expect(data).toContain(`type AllMappedModels = MaybeOrArrayOfMaybe<Todo>`) }) test('respects user provided codegen config', async () => { const customCodegenConfigPath = path.join(FIXTURE_PATH, 'codegen.yml') // Add codegen.yml to fixture folder fs.writeFileSync( customCodegenConfigPath, `config: omitOperationSuffix: false namingConvention: typeNames: change-case-all#upperCase` ) // Wrapping in `try` to make sure codegen.yml is always deleted, even if the // test fails try { await generateGraphQLSchema() const { typeDefFiles: [outputPath], } = await generateTypeDefGraphQLWeb() const gqlTypesOutput = fs.readFileSync(outputPath, 'utf-8') // Should be upper cased type expect(gqlTypesOutput).toContain('ADDTODO_CREATETODOMUTATION') // because we override omitOperationSuffix to false, it should append QUERY // for __fixtures__/example-todo-main/../NumTodosCell.js expect(gqlTypesOutput).toContain('NUMTODOSCELL_GETCOUNTQUERY') } finally { // Delete added codegen.yml fs.rmSync(customCodegenConfigPath) } }) test("Doesn't throw or print any errors with empty project", async () => { const fixturePath = path.resolve( __dirname, '../../../../__fixtures__/empty-project' ) process.env.RWJS_CWD = fixturePath const oldConsoleError = console.error console.error = jest.fn() try { await generateGraphQLSchema() await generateTypeDefGraphQLWeb() await generateTypeDefGraphQLApi() } catch (e) { console.error(e) // Fail if any of the three above calls throws an error expect(false).toBeTruthy() } try { expect(console.error).not.toHaveBeenCalled() } finally { console.error = oldConsoleError delete process.env.RWJS_CWD } }) describe("Doesn't swallow legit errors", () => { test('invalidQueryType', async () => { const fixturePath = path.resolve( __dirname, './fixtures/graphqlCodeGen/invalidQueryType' ) process.env.RWJS_CWD = fixturePath const { errors } = await generateTypeDefGraphQLWeb() expect((errors[0].error as Error).toString()).toMatch( /field.*softKitten.*Query/ ) delete process.env.RWJS_CWD }) test('missingType', async () => { const fixturePath = path.resolve( __dirname, './fixtures/graphqlCodeGen/missingType' ) process.env.RWJS_CWD = fixturePath const { errors } = await generateTypeDefGraphQLWeb() expect((errors[0].error as Error).toString()).toMatch(/Unknown type.*Todo/) delete process.env.RWJS_CWD }) test('nonExistingField', async () => { const fixturePath = path.resolve( __dirname, './fixtures/graphqlCodeGen/nonExistingField' ) process.env.RWJS_CWD = fixturePath const { errors } = await generateTypeDefGraphQLWeb() expect((errors[0].error as Error).toString()).toMatch(/field.*done.*Todo/) delete process.env.RWJS_CWD }) })
5,553
0
petrpan-code/redwoodjs/redwood/packages/internal/src
petrpan-code/redwoodjs/redwood/packages/internal/src/__tests__/graphqlSchema.test.ts
import fs from 'fs' import path from 'path' import chalk from 'chalk' import terminalLink from 'terminal-link' import { generateGraphQLSchema } from '../generate/graphqlSchema' const FIXTURE_PATH = path.resolve( __dirname, '../../../../__fixtures__/example-todo-main' ) beforeAll(() => { process.env.RWJS_CWD = FIXTURE_PATH }) afterAll(() => { delete process.env.RWJS_CWD }) afterEach(() => { jest.restoreAllMocks() }) test('Generates GraphQL schema', async () => { const expectedPath = path.join(FIXTURE_PATH, '.redwood', 'schema.graphql') jest .spyOn(fs, 'writeFileSync') .mockImplementation( (file: fs.PathOrFileDescriptor, data: string | ArrayBufferView) => { expect(file).toMatch(expectedPath) expect(data).toMatchSnapshot() } ) const { schemaPath } = await generateGraphQLSchema() expect(schemaPath).toMatch(expectedPath) }) test('Includes live query directive if serverful and realtime ', async () => { const fixturePath = path.resolve( __dirname, './fixtures/graphqlCodeGen/realtime' ) process.env.RWJS_CWD = fixturePath const expectedPath = path.join(fixturePath, '.redwood', 'schema.graphql') jest .spyOn(fs, 'writeFileSync') .mockImplementation( (file: fs.PathOrFileDescriptor, data: string | ArrayBufferView) => { expect(file).toMatch(expectedPath) expect(data).toMatchSnapshot() } ) await generateGraphQLSchema() }) test('Returns error message when schema loading fails', async () => { const fixturePath = path.resolve( __dirname, './fixtures/graphqlCodeGen/bookshelf' ) process.env.RWJS_CWD = fixturePath try { const { errors } = await generateGraphQLSchema() const [schemaLoadingError] = errors console.log({ errors, }) expect(schemaLoadingError.message).toEqual( [ 'Schema loading failed. Unknown type: "Shelf".', '', ` ${chalk.bgYellow(` ${chalk.black.bold('Heads up')} `)}`, '', chalk.yellow( ` It looks like you have a Shelf model in your Prisma schema.` ), chalk.yellow( ` If it's part of a relation, you may have to generate SDL or scaffolding for Shelf too.` ), chalk.yellow( ` So, if you haven't done that yet, ignore this error message and run the SDL or scaffold generator for Shelf now.` ), '', chalk.yellow( ` See the ${terminalLink( 'Troubleshooting Generators', 'https://redwoodjs.com/docs/schema-relations#troubleshooting-generators' )} section in our docs for more help.` ), ].join('\n') ) } finally { delete process.env.RWJS_CWD } })
5,554
0
petrpan-code/redwoodjs/redwood/packages/internal/src
petrpan-code/redwoodjs/redwood/packages/internal/src/__tests__/jsx.test.ts
import path from 'path' import { fileToAst } from '../ast' import { getJsxElements } from '../jsx' const getFixturePath = (relativeFilePath: string) => { return path.join(__dirname, `fixtures/${relativeFilePath}`) } test('simple jsx tree', () => { const simpleAst = fileToAst(getFixturePath('web/src/router/simple.tsx')) const elements = getJsxElements(simpleAst, 'Router') expect(elements).toMatchInlineSnapshot(` [ { "children": [ { "children": [ { "children": [], "location": { "column": 8, "line": 5, }, "name": "Route", "props": { "name": "home", "page": "HomePage", "path": "/home", }, }, { "children": [], "location": { "column": 8, "line": 6, }, "name": "Route", "props": { "name": "login", "page": "LoginPage", "path": "/login", }, }, { "children": [], "location": { "column": 8, "line": 7, }, "name": "Route", "props": { "name": "404", "page": "ArrowFunctionExpression is not supported", "path": "/404", }, }, ], "location": { "column": 6, "line": 4, }, "name": "Set", "props": { "private": true, }, }, ], "location": { "column": 4, "line": 3, }, "name": "Router", "props": {}, }, ] `) })
5,555
0
petrpan-code/redwoodjs/redwood/packages/internal/src
petrpan-code/redwoodjs/redwood/packages/internal/src/__tests__/nestedPages.test.ts
import path from 'path' import { expect } from '@jest/globals' import { prebuildWebFile } from '@redwoodjs/babel-config' import { getPaths } from '@redwoodjs/project-config' import { cleanWebBuild } from '../build/web' const FIXTURE_PATH = path.join(__dirname, 'fixtures/nestedPages') function normalizeStr(str: string) { return str .split('\n') .map((line) => line.trim()) .join('\n') .trim() } describe('User specified imports, with static imports', () => { let outputWithStaticImports: string | null | undefined let outputNoStaticImports: string | null | undefined beforeEach(() => { process.env.RWJS_CWD = FIXTURE_PATH cleanWebBuild() }) afterAll(() => { delete process.env.RWJS_CWD }) beforeAll(() => { process.env.RWJS_CWD = FIXTURE_PATH const routesFile = getPaths().web.routes outputWithStaticImports = prebuildWebFile(routesFile, { prerender: true, forJest: true, })?.code outputWithStaticImports &&= normalizeStr(outputWithStaticImports) outputNoStaticImports = prebuildWebFile(routesFile, { forJest: true, })?.code outputNoStaticImports &&= normalizeStr(outputNoStaticImports) }) it('Imports layouts correctly', () => { // Note avoid checking the full require path because windows paths have unusual slashes expect(outputWithStaticImports).toContain( `var _AdminLayout = _interopRequireDefault(require("` ) expect(outputWithStaticImports).toContain( `var _MainLayout = _interopRequireDefault(require("` ) expect(outputNoStaticImports).toContain( `var _AdminLayout = _interopRequireDefault(require("` ) expect(outputNoStaticImports).toContain( `var _MainLayout = _interopRequireDefault(require("` ) }) describe('pages without explicit import', () => { describe('static prerender imports', () => { it('Adds loaders for non-nested pages', () => { expect(outputWithStaticImports).toContain( normalizeStr( `const LoginPage = { name: "LoginPage", prerenderLoader: name => require("./pages/LoginPage/LoginPage"), LazyComponent: (0, _react.lazy)(() => import( /* webpackChunkName: "LoginPage" */"./pages/LoginPage/LoginPage")) }` ) ) expect(outputWithStaticImports).toContain( normalizeStr( `const HomePage = { name: "HomePage", prerenderLoader: name => require("./pages/HomePage/HomePage"), LazyComponent: (0, _react.lazy)(() => import( /* webpackChunkName: "HomePage" */"./pages/HomePage/HomePage")) };` ) ) }) }) describe('dynamic build imports', () => { it('Adds loaders for non-nested pages with __webpack_require__ and require.resolveWeak in prerenderLoader to not bundle the pages', () => { expect(outputNoStaticImports).toContain( normalizeStr( `const LoginPage = { name: "LoginPage", prerenderLoader: name => __webpack_require__(require.resolveWeak("./pages/LoginPage/LoginPage")), LazyComponent: (0, _react.lazy)(() => import( /* webpackChunkName: "LoginPage" */"./pages/LoginPage/LoginPage")) }` ) ) expect(outputNoStaticImports).toContain( normalizeStr( `const HomePage = { name: "HomePage", prerenderLoader: name => __webpack_require__(require.resolveWeak("./pages/HomePage/HomePage")), LazyComponent: (0, _react.lazy)(() => import( /* webpackChunkName: "HomePage" */"./pages/HomePage/HomePage")) }` ) ) }) }) }) describe('pages with explicit import', () => { describe('static prerender imports', () => { it('Uses the user specified name for nested page', () => { // Import statement: import NewJobPage from 'src/pages/Jobs/NewJobPage' expect(outputWithStaticImports).toContain( normalizeStr( `const NewJobPage = { name: "NewJobPage", prerenderLoader: name => require("./pages/Jobs/NewJobPage/NewJobPage"), LazyComponent: (0, _react.lazy)(() => import( /* webpackChunkName: "NewJobPage" */"./pages/Jobs/NewJobPage/NewJobPage")) }` ) ) }) it('Uses the user specified custom default export import name for nested page', () => { // Import statement: import BazingaJobProfilePageWithFunnyName from 'src/pages/Jobs/JobProfilePage' expect(outputWithStaticImports).toContain( normalizeStr( `const BazingaJobProfilePageWithFunnyName = { name: "BazingaJobProfilePageWithFunnyName", prerenderLoader: name => require("./pages/Jobs/JobProfilePage/JobProfilePage"), LazyComponent: (0, _react.lazy)(() => import( /* webpackChunkName: "BazingaJobProfilePageWithFunnyName" */"./pages/Jobs/JobProfilePage/JobProfilePage")) }` ) ) }) it('Removes explicit imports when prerendering', () => { expect(outputWithStaticImports).not.toContain( `var _NewJobPage = _interopRequireDefault` ) expect(outputWithStaticImports).not.toContain( `var _JobProfilePage = _interopRequireDefault` ) }) it('Keeps using the user specified name when generating React component', () => { // Generate react component still uses the user specified name expect(outputWithStaticImports).toContain( normalizeStr( `}), /*#__PURE__*/(0, _jsxRuntime.jsx)(_router.Route, { path: "/job-profiles/{id:Int}", page: BazingaJobProfilePageWithFunnyName, name: "jobProfile"` ) ) }) }) describe('dynamic build imports', () => { it('Directly uses the import when page is explicitly imported', () => { // Explicit import uses the specified import // Has statement: import BazingaJobProfilePageWithFunnyName from 'src/pages/Jobs/JobProfilePage' // The name of the import is not important without static imports expect(outputNoStaticImports).toContain( normalizeStr( `}), /*#__PURE__*/(0, _jsxRuntime.jsx)(_router.Route, { path: "/job-profiles/{id:Int}", page: _JobProfilePage["default"], name: "jobProfile" })` ) ) }) it("Uses the LazyComponent for a page that isn't imported", () => { expect(outputNoStaticImports).toContain( normalizeStr( `const HomePage = { name: "HomePage", prerenderLoader: name => __webpack_require__(require.resolveWeak("./pages/HomePage/HomePage")), LazyComponent: (0, _react.lazy)(() => import( /* webpackChunkName: "HomePage" */"./pages/HomePage/HomePage")) }` ) ) expect(outputNoStaticImports).toContain( normalizeStr( `}), /*#__PURE__*/(0, _jsxRuntime.jsx)(_router.Route, { path: "/", page: HomePage, name: "home" })` ) ) }) it('Should NOT add a LazyComponent for pages that have been explicitly loaded', () => { expect(outputNoStaticImports).not.toContain( normalizeStr( `const JobsJobPage = { name: "JobsJobPage"` ) ) expect(outputNoStaticImports).not.toContain( normalizeStr( `const JobsNewJobPage = { name: "JobsNewJobPage"` ) ) expect(outputNoStaticImports).toContain( normalizeStr( `}), /*#__PURE__*/(0, _jsxRuntime.jsx)(_router.Route, { path: "/jobs", page: _JobsPage["default"], name: "jobs" })` ) ) }) }) }) it('Handles when imports from a page include non-default imports too', () => { // Because we import import EditJobPage, πŸ‘‰ { NonDefaultExport } from 'src/pages/Jobs/EditJobPage' expect(outputWithStaticImports).toContain('var _EditJobPage = require("') expect(outputWithStaticImports).toContain( normalizeStr( `const EditJobPage = { name: "EditJobPage", prerenderLoader: name => require("./pages/Jobs/EditJobPage/EditJobPage"), LazyComponent: (0, _react.lazy)(() => import( /* webpackChunkName: "EditJobPage" */"./pages/Jobs/EditJobPage/EditJobPage")) }` ) ) expect(outputNoStaticImports).toContain( 'var _EditJobPage = _interopRequireWildcard(' ) expect(outputNoStaticImports).toContain( normalizeStr( `}), /*#__PURE__*/(0, _jsxRuntime.jsx)(_router.Route, { path: "/jobs/{id:Int}/edit", page: _EditJobPage["default"], name: "editJob"` ) ) // Should not generate a loader, because page was explicitly imported expect(outputNoStaticImports).not.toMatch( /import\(.*"\.\/pages\/Jobs\/EditJobPage\/EditJobPage"\)/ ) }) })
5,556
0
petrpan-code/redwoodjs/redwood/packages/internal/src
petrpan-code/redwoodjs/redwood/packages/internal/src/__tests__/possibleTypes.test.ts
import fs from 'fs' import path from 'path' import { getPaths } from '@redwoodjs/project-config' import { generateGraphQLSchema } from '../generate/graphqlSchema' import { generatePossibleTypes } from '../generate/possibleTypes' afterEach(() => { delete process.env.RWJS_CWD jest.restoreAllMocks() }) describe('Generate gql possible types web from the GraphQL Schema', () => { describe('when toml has graphql possible types turned off', () => { test('when there are *no* union types', async () => { const FIXTURE_PATH = path.resolve( __dirname, '../../../../__fixtures__/example-todo-main' ) process.env.RWJS_CWD = FIXTURE_PATH await generateGraphQLSchema() jest .spyOn(fs, 'writeFileSync') .mockImplementation( (file: fs.PathOrFileDescriptor, data: string | ArrayBufferView) => { expect(file).toMatch( path.join(getPaths().web.graphql, 'possibleTypes.ts') ) expect(data).toMatchSnapshot() } ) const { possibleTypesFiles } = await generatePossibleTypes() expect(possibleTypesFiles).toHaveLength(0) }) }) describe('when toml has graphql possible types turned om', () => { test('when there are union types ', async () => { const FIXTURE_PATH = path.resolve( __dirname, '../../../../__fixtures__/fragment-test-project' ) process.env.RWJS_CWD = FIXTURE_PATH await generateGraphQLSchema() jest .spyOn(fs, 'writeFileSync') .mockImplementation( (file: fs.PathOrFileDescriptor, data: string | ArrayBufferView) => { expect(file).toMatch( path.join(getPaths().web.graphql, 'possibleTypes.ts') ) expect(data).toMatchSnapshot() } ) const { possibleTypesFiles } = await generatePossibleTypes() expect(possibleTypesFiles).toHaveLength(1) expect(possibleTypesFiles[0]).toMatch( path.join(getPaths().web.graphql, 'possibleTypes.ts') ) }) }) })
5,557
0
petrpan-code/redwoodjs/redwood/packages/internal/src
petrpan-code/redwoodjs/redwood/packages/internal/src/__tests__/project.test.ts
import path from 'path' import { getTsConfigs } from '../project' describe('Retrieves TSConfig settings', () => { afterAll(() => { delete process.env.RWJS_CWD }) it('Gets config for a TS Project', () => { const TS_FIXTURE_PATH = getFixtureDir('test-project') process.env.RWJS_CWD = TS_FIXTURE_PATH const tsConfiguration = getTsConfigs() expect(tsConfiguration.web).not.toBe(null) expect(tsConfiguration.api).not.toBe(null) // Check some of the values expect(tsConfiguration.web.compilerOptions.noEmit).toBe(true) expect(tsConfiguration.api.compilerOptions.rootDirs).toEqual([ './src', '../.redwood/types/mirror/api/src', ]) }) it('Returns null for JS projects', () => { const JS_FIXTURE_PATH = getFixtureDir('example-todo-main-with-errors') process.env.RWJS_CWD = JS_FIXTURE_PATH const tsConfiguration = getTsConfigs() expect(tsConfiguration.web).toBe(null) expect(tsConfiguration.api).toBe(null) }) }) function getFixtureDir( name: | 'example-todo-main-with-errors' | 'example-todo-main' | 'empty-project' | 'test-project' ) { return path.resolve(__dirname, `../../../../__fixtures__/${name}`) }
5,558
0
petrpan-code/redwoodjs/redwood/packages/internal/src
petrpan-code/redwoodjs/redwood/packages/internal/src/__tests__/resolverFn.test.ts
import path from 'path' import { getResolverFnType } from '../generate/graphqlCodeGen' const FIXTURE_PATH = path.resolve( __dirname, '../../../../__fixtures__/example-todo-main' ) // Pretend project is strict-mode let mockedTSConfigs = { api: null, web: null, } jest.mock('../project', () => { return { getTsConfigs: () => { return mockedTSConfigs }, } }) beforeAll(() => { process.env.RWJS_CWD = FIXTURE_PATH }) afterAll(() => { delete process.env.RWJS_CWD }) afterEach(() => { jest.restoreAllMocks() }) describe('ResovlerFn types', () => { it('Uses optional function args on JS projects', () => { // Note args and obj are optional expect(getResolverFnType()).toMatchInlineSnapshot(` "( args?: TArgs, obj?: { root: TParent; context: TContext; info: GraphQLResolveInfo } ) => TResult | Promise<TResult>" `) }) it('Uses optional function args when strict mode is off', () => { mockedTSConfigs = { api: { compilerOptions: { strict: false, }, }, web: null, } // Note args and obj are optional expect(getResolverFnType()).toMatchInlineSnapshot(` "( args?: TArgs, obj?: { root: TParent; context: TContext; info: GraphQLResolveInfo } ) => TResult | Promise<TResult>" `) }) it('ResolverFn uses non-optional function args in strict mode', async () => { // Prertend project is strict mode mockedTSConfigs = { api: { compilerOptions: { strict: true, }, }, web: null, } // Note args and obj are NOT optional expect(getResolverFnType()).toMatchInlineSnapshot(` "( args: TArgs, obj?: { root: TParent; context: TContext; info: GraphQLResolveInfo } ) => TResult | Promise<TResult>" `) }) })