level_0
int64
0
10k
index
int64
0
0
repo_id
stringlengths
22
152
file_path
stringlengths
41
203
content
stringlengths
11
11.5M
2,079
0
petrpan-code/nrwl/nx/e2e/vue
petrpan-code/nrwl/nx/e2e/vue/src/vue-tailwind.test.ts
import { cleanupProject, listFiles, newProject, readFile, runCLI, uniq, updateFile, } from '@nx/e2e/utils'; describe('vue tailwind support', () => { beforeAll(() => { newProject({ unsetProjectNameAndRootFormat: false }); }); afterAll(() => { cleanupProject(); }); it('should setup tailwind and build correctly', async () => { const app = uniq('app'); runCLI(`generate @nx/vue:app ${app} --style=css --no-interactive`); runCLI(`generate @nx/vue:setup-tailwind --project=${app}`); updateFile( `${app}/src/App.vue`, ` <template> <h1 className='text-3xl font-bold'> Hello TailwindCSS! </h1> </template> ` ); runCLI(`build ${app}`); const fileArray = listFiles(`dist/${app}/assets`); const stylesheet = fileArray.find((file) => file.endsWith('.css')); const content = readFile(`dist/${app}/assets/${stylesheet}`); // used, not purged expect(content).toContain('text-3xl'); expect(content).toContain('font-bold'); // unused, purged expect(content).not.toContain('text-xl'); }, 300_000); });
2,080
0
petrpan-code/nrwl/nx/e2e/vue
petrpan-code/nrwl/nx/e2e/vue/src/vue.test.ts
import { cleanupProject, killPorts, newProject, runCLI, runE2ETests, uniq, } from '@nx/e2e/utils'; describe('Vue Plugin', () => { let proj: string; beforeAll(() => { proj = newProject({ unsetProjectNameAndRootFormat: false, }); }); afterAll(() => cleanupProject()); // TODO: enable this when tests are passing again. xit('should serve application in dev mode', async () => { const app = uniq('app'); runCLI( `generate @nx/vue:app ${app} --unitTestRunner=vitest --e2eTestRunner=playwright` ); let result = runCLI(`test ${app}`); expect(result).toContain(`Successfully ran target test for project ${app}`); result = runCLI(`build ${app}`); expect(result).toContain( `Successfully ran target build for project ${app}` ); if (runE2ETests()) { const e2eResults = runCLI(`e2e ${app}-e2e --no-watch`); expect(e2eResults).toContain('Successfully ran target e2e'); expect(await killPorts()).toBeTruthy(); } }, 200_000); it('should build library', async () => { const lib = uniq('lib'); runCLI( `generate @nx/vue:lib ${lib} --bundler=vite --unitTestRunner=vitest` ); const result = runCLI(`build ${lib}`); expect(result).toContain( `Successfully ran target build for project ${lib}` ); }); });
2,085
0
petrpan-code/nrwl/nx/e2e/web
petrpan-code/nrwl/nx/e2e/web/src/file-server.test.ts
import { cleanupProject, killPorts, newProject, promisifiedTreeKill, runCLI, runCommandUntil, setMaxWorkers, uniq, updateJson, } from '@nx/e2e/utils'; import { join } from 'path'; describe('file-server', () => { beforeAll(() => { newProject({ name: uniq('fileserver') }); }); afterAll(() => cleanupProject()); it('should serve folder of files', async () => { const appName = uniq('app'); const port = 4301; runCLI(`generate @nx/web:app ${appName} --no-interactive`); setMaxWorkers(join('apps', appName, 'project.json')); updateJson(join('apps', appName, 'project.json'), (config) => { config.targets['serve'].executor = '@nx/web:file-server'; return config; }); const p = await runCommandUntil( `serve ${appName} --port=${port}`, (output) => { return output.indexOf(`localhost:${port}`) > -1; } ); try { await promisifiedTreeKill(p.pid, 'SIGKILL'); await killPorts(port); } catch { // ignore } }, 300_000); it('should setup and serve static files from app', async () => { const ngAppName = uniq('ng-app'); const reactAppName = uniq('react-app'); runCLI( `generate @nx/angular:app ${ngAppName} --no-interactive --e2eTestRunner=none` ); runCLI( `generate @nx/react:app ${reactAppName} --no-interactive --e2eTestRunner=none` ); runCLI( `generate @nx/web:static-config --buildTarget=${ngAppName}:build --no-interactive` ); runCLI( `generate @nx/web:static-config --buildTarget=${reactAppName}:build --targetName=custom-serve-static --no-interactive` ); setMaxWorkers(join('apps', reactAppName, 'project.json')); const port = 6200; const ngServe = await runCommandUntil( `serve-static ${ngAppName} --port=${port}`, (output) => { return output.indexOf(`localhost:${port}`) > -1; } ); try { await promisifiedTreeKill(ngServe.pid, 'SIGKILL'); await killPorts(port); } catch { // ignore } const reactServe = await runCommandUntil( `custom-serve-static ${reactAppName} --port=${port + 1}`, (output) => { return output.indexOf(`localhost:${port + 1}`) > -1; } ); try { await promisifiedTreeKill(reactServe.pid, 'SIGKILL'); await killPorts(port + 1); } catch { // ignore } }, 300_000); });
2,086
0
petrpan-code/nrwl/nx/e2e/web
petrpan-code/nrwl/nx/e2e/web/src/web-vite.test.ts
import { checkFilesDoNotExist, checkFilesExist, cleanupProject, createFile, isNotWindows, killPorts, newProject, runCLI, runCLIAsync, runE2ETests, setMaxWorkers, uniq, } from '@nx/e2e/utils'; import { join } from 'path'; describe('Web Components Applications with bundler set as vite', () => { beforeEach(() => newProject()); afterEach(() => cleanupProject()); it('should be able to generate a web app', async () => { const appName = uniq('app'); runCLI(`generate @nx/web:app ${appName} --bundler=vite --no-interactive`); setMaxWorkers(join('apps', appName, 'project.json')); const lintResults = runCLI(`lint ${appName}`); expect(lintResults).toContain('All files pass linting.'); runCLI(`build ${appName}`); checkFilesExist(`dist/apps/${appName}/index.html`); const testResults = await runCLIAsync(`test ${appName}`); expect(testResults.combinedOutput).toContain('Tests 2 passed (2)'); const lintE2eResults = runCLI(`lint ${appName}-e2e`); expect(lintE2eResults).toContain('All files pass linting.'); if (isNotWindows() && runE2ETests()) { const e2eResults = runCLI(`e2e ${appName}-e2e --no-watch`); expect(e2eResults).toContain('All specs passed!'); expect(await killPorts()).toBeTruthy(); } }, 500000); it('should remove previous output before building', async () => { const appName = uniq('app'); const libName = uniq('lib'); runCLI(`generate @nx/web:app ${appName} --bundler=vite --no-interactive`); runCLI( `generate @nx/react:lib ${libName} --bundler=vite --no-interactive --unitTestRunner=vitest` ); setMaxWorkers(join('apps', appName, 'project.json')); createFile(`dist/apps/${appName}/_should_remove.txt`); createFile(`dist/libs/${libName}/_should_remove.txt`); createFile(`dist/apps/_should_not_remove.txt`); checkFilesExist( `dist/apps/${appName}/_should_remove.txt`, `dist/apps/_should_not_remove.txt` ); runCLI(`build ${appName}`); runCLI(`build ${libName}`); checkFilesDoNotExist( `dist/apps/${appName}/_should_remove.txt`, `dist/libs/${libName}/_should_remove.txt` ); checkFilesExist(`dist/apps/_should_not_remove.txt`); }, 120000); });
2,087
0
petrpan-code/nrwl/nx/e2e/web
petrpan-code/nrwl/nx/e2e/web/src/web-webpack.test.ts
import { cleanupProject, newProject, runCLI, runCommandUntil, setMaxWorkers, uniq, } from '@nx/e2e/utils'; import { join } from 'path'; describe('Web Components Applications with bundler set as webpack', () => { beforeEach(() => newProject()); afterEach(() => cleanupProject()); it('should support https for dev-server', async () => { const appName = uniq('app'); runCLI( `generate @nx/web:app ${appName} --bundler=webpack --no-interactive` ); setMaxWorkers(join('apps', appName, 'project.json')); await runCommandUntil(`serve ${appName} --port=5000 --ssl`, (output) => { return output.includes('listening at https://localhost:5000'); }); }, 300_000); });
2,088
0
petrpan-code/nrwl/nx/e2e/web
petrpan-code/nrwl/nx/e2e/web/src/web.test.ts
import { checkFilesDoNotExist, checkFilesExist, cleanupProject, createFile, ensurePlaywrightBrowsersInstallation, isNotWindows, killPorts, newProject, readFile, rmDist, runCLI, runCLIAsync, runE2ETests, setMaxWorkers, tmpProjPath, uniq, updateFile, updateJson, } from '@nx/e2e/utils'; import { join } from 'path'; import { copyFileSync } from 'fs'; describe('Web Components Applications', () => { beforeEach(() => newProject()); afterEach(() => cleanupProject()); it('should be able to generate a web app', async () => { const appName = uniq('app'); runCLI( `generate @nx/web:app ${appName} --bundler=webpack --no-interactive` ); setMaxWorkers(join('apps', appName, 'project.json')); const lintResults = runCLI(`lint ${appName}`); expect(lintResults).toContain('All files pass linting.'); const testResults = await runCLIAsync(`test ${appName}`); expect(testResults.combinedOutput).toContain( 'Test Suites: 1 passed, 1 total' ); const lintE2eResults = runCLI(`lint ${appName}-e2e`); expect(lintE2eResults).toContain('All files pass linting.'); if (isNotWindows() && runE2ETests()) { const e2eResults = runCLI(`e2e ${appName}-e2e --no-watch`); expect(e2eResults).toContain('All specs passed!'); expect(await killPorts()).toBeTruthy(); } copyFileSync( join(__dirname, 'test-fixtures/inlined.png'), join(tmpProjPath(), `apps/${appName}/src/app/inlined.png`) ); copyFileSync( join(__dirname, 'test-fixtures/emitted.png'), join(tmpProjPath(), `apps/${appName}/src/app/emitted.png`) ); updateFile( `apps/${appName}/src/app/app.element.ts`, ` // @ts-ignore import inlined from './inlined.png'; // @ts-ignore import emitted from './emitted.png'; export class AppElement extends HTMLElement { public static observedAttributes = []; connectedCallback() { this.innerHTML = \` <img src="\${inlined} "/> <img src="\${emitted} "/> \`; } } customElements.define('app-root', AppElement); ` ); runCLI(`build ${appName} --outputHashing none`); checkFilesExist( `dist/apps/${appName}/index.html`, `dist/apps/${appName}/runtime.js`, `dist/apps/${appName}/emitted.png`, `dist/apps/${appName}/main.js`, `dist/apps/${appName}/styles.css` ); checkFilesDoNotExist(`dist/apps/${appName}/inlined.png`); expect(readFile(`dist/apps/${appName}/main.js`)).toContain( '<img src="data:image/png;base64' ); // Should not be a JS module but kept as a PNG expect(readFile(`dist/apps/${appName}/emitted.png`)).not.toContain( 'export default' ); expect(readFile(`dist/apps/${appName}/index.html`)).toContain( '<link rel="stylesheet" href="styles.css">' ); }, 500000); // TODO: re-enable this when tests are passing again xit('should generate working playwright e2e app', async () => { const appName = uniq('app'); runCLI( `generate @nx/web:app ${appName} --bundler=webpack --e2eTestRunner=playwright --no-interactive` ); setMaxWorkers(join('apps', appName, 'project.json')); const lintE2eResults = runCLI(`lint ${appName}-e2e`); expect(lintE2eResults).toContain('All files pass linting.'); if (isNotWindows() && runE2ETests()) { ensurePlaywrightBrowsersInstallation(); const e2eResults = runCLI(`e2e ${appName}-e2e`); expect(e2eResults).toContain( `Successfully ran target e2e for project ${appName}-e2e` ); expect(await killPorts()).toBeTruthy(); } }, 500000); it('should remove previous output before building', async () => { const appName = uniq('app'); const libName = uniq('lib'); runCLI( `generate @nx/web:app ${appName} --bundler=webpack --no-interactive --compiler swc` ); runCLI( `generate @nx/react:lib ${libName} --bundler=rollup --no-interactive --compiler swc --unitTestRunner=jest` ); setMaxWorkers(join('apps', appName, 'project.json')); createFile(`dist/apps/${appName}/_should_remove.txt`); createFile(`dist/libs/${libName}/_should_remove.txt`); createFile(`dist/apps/_should_not_remove.txt`); checkFilesExist( `dist/apps/${appName}/_should_remove.txt`, `dist/apps/_should_not_remove.txt` ); runCLI(`build ${appName} --outputHashing none`); runCLI(`build ${libName}`); checkFilesDoNotExist( `dist/apps/${appName}/_should_remove.txt`, `dist/libs/${libName}/_should_remove.txt` ); checkFilesExist(`dist/apps/_should_not_remove.txt`); // Asset that React runtime is imported expect(readFile(`dist/libs/${libName}/index.esm.js`)).toMatch( /react\/jsx-runtime/ ); // `delete-output-path` createFile(`dist/apps/${appName}/_should_keep.txt`); runCLI(`build ${appName} --delete-output-path=false --outputHashing none`); checkFilesExist(`dist/apps/${appName}/_should_keep.txt`); createFile(`dist/libs/${libName}/_should_keep.txt`); runCLI(`build ${libName} --delete-output-path=false --outputHashing none`); checkFilesExist(`dist/libs/${libName}/_should_keep.txt`); }, 120000); it('should emit decorator metadata when --compiler=babel and it is enabled in tsconfig', async () => { const appName = uniq('app'); runCLI( `generate @nx/web:app ${appName} --bundler=webpack --compiler=babel --no-interactive` ); setMaxWorkers(join('apps', appName, 'project.json')); updateFile(`apps/${appName}/src/app/app.element.ts`, (content) => { const newContent = `${content} function enumerable(value: boolean) { return function ( target: any, propertyKey: string, descriptor: PropertyDescriptor ) { descriptor.enumerable = value; }; } function sealed(target: any) { return target; } @sealed class Foo { @enumerable(false) bar() {} } `; return newContent; }); updateFile(`apps/${appName}/src/app/app.element.ts`, (content) => { const newContent = `${content} // bust babel and nx cache `; return newContent; }); runCLI(`build ${appName} --outputHashing none`); expect(readFile(`dist/apps/${appName}/main.js`)).toMatch( /Reflect\.metadata/ ); // Turn off decorator metadata updateFile(`apps/${appName}/tsconfig.app.json`, (content) => { const json = JSON.parse(content); json.compilerOptions.emitDecoratorMetadata = false; return JSON.stringify(json); }); runCLI(`build ${appName} --outputHashing none`); expect(readFile(`dist/apps/${appName}/main.js`)).not.toMatch( /Reflect\.metadata/ ); }, 120000); it('should emit decorator metadata when using --compiler=swc', async () => { const appName = uniq('app'); runCLI( `generate @nx/web:app ${appName} --bundler=webpack --compiler=swc --no-interactive` ); setMaxWorkers(join('apps', appName, 'project.json')); updateFile(`apps/${appName}/src/app/app.element.ts`, (content) => { const newContent = `${content} function enumerable(value: boolean) { return function ( target: any, propertyKey: string, descriptor: PropertyDescriptor ) { descriptor.enumerable = value; }; } function sealed(target: any) { return target; } @sealed class Foo { @enumerable(false) bar() {} } `; return newContent; }); updateFile(`apps/${appName}/src/app/app.element.ts`, (content) => { const newContent = `${content} // bust babel and nx cache `; return newContent; }); runCLI(`build ${appName} --outputHashing none`); expect(readFile(`dist/apps/${appName}/main.js`)).toMatch( /Foo=.*?_decorate/ ); }, 120000); it('should support custom webpackConfig option', async () => { const appName = uniq('app'); runCLI( `generate @nx/web:app ${appName} --bundler=webpack --no-interactive` ); setMaxWorkers(join('apps', appName, 'project.json')); updateJson(join('apps', appName, 'project.json'), (config) => { config.targets.build.options.webpackConfig = `apps/${appName}/webpack.config.js`; return config; }); // Return sync function updateFile( `apps/${appName}/webpack.config.js`, ` const { composePlugins, withNx, withWeb } = require('@nx/webpack'); module.exports = composePlugins(withNx(), withWeb(), (config, context) => { return config; }); ` ); runCLI(`build ${appName} --outputHashing none`); checkFilesExist(`dist/apps/${appName}/main.js`); rmDist(); // Return async function updateFile( `apps/${appName}/webpack.config.js`, ` const { composePlugins, withNx, withWeb } = require('@nx/webpack'); module.exports = composePlugins(withNx(), withWeb(), async (config, context) => { return config; }); ` ); runCLI(`build ${appName} --outputHashing none`); checkFilesExist(`dist/apps/${appName}/main.js`); rmDist(); // Return promise of function updateFile( `apps/${appName}/webpack.config.js`, ` const { composePlugins, withNx, withWeb } = require('@nx/webpack'); module.exports = composePlugins(withNx(), withWeb(), Promise.resolve((config, context) => { return config; })); ` ); runCLI(`build ${appName} --outputHashing none`); checkFilesExist(`dist/apps/${appName}/main.js`); }, 100000); it('should support generating applications with the new name and root format', () => { const appName = uniq('app1'); runCLI( `generate @nx/web:app ${appName} --bundler=webpack --project-name-and-root-format=as-provided --no-interactive` ); // check files are generated without the layout directory ("apps/") and // using the project name as the directory when no directory is provided checkFilesExist(`${appName}/src/main.ts`); // check build works expect(runCLI(`build ${appName}`)).toContain( `Successfully ran target build for project ${appName}` ); // check tests pass const appTestResult = runCLI(`test ${appName}`); expect(appTestResult).toContain( `Successfully ran target test for project ${appName}` ); }, 500_000); }); describe('CLI - Environment Variables', () => { it('should automatically load workspace and per-project environment variables', async () => { newProject(); const appName = uniq('app'); //test if the Nx CLI loads root .env vars updateFile( `.env`, 'NX_WS_BASE=ws-base\nNX_SHARED_ENV=shared-in-workspace-base' ); updateFile( `.env.local`, 'NX_WS_ENV_LOCAL=ws-env-local\nNX_SHARED_ENV=shared-in-workspace-env-local' ); updateFile( `.local.env`, 'NX_WS_LOCAL_ENV=ws-local-env\nNX_SHARED_ENV=shared-in-workspace-local-env' ); updateFile( `apps/${appName}/.env`, 'NX_APP_BASE=app-base\nNX_SHARED_ENV=shared-in-app-base' ); updateFile( `apps/${appName}/.env.local`, 'NX_APP_ENV_LOCAL=app-env-local\nNX_SHARED_ENV=shared-in-app-env-local' ); updateFile( `apps/${appName}/.local.env`, 'NX_APP_LOCAL_ENV=app-local-env\nNX_SHARED_ENV=shared-in-app-local-env' ); const main = `apps/${appName}/src/main.ts`; const newCode = ` const envVars = [process.env.NODE_ENV, process.env.NX_BUILD, process.env.NX_API, process.env.NX_WS_BASE, process.env.NX_WS_ENV_LOCAL, process.env.NX_WS_LOCAL_ENV, process.env.NX_APP_BASE, process.env.NX_APP_ENV_LOCAL, process.env.NX_APP_LOCAL_ENV, process.env.NX_SHARED_ENV]; const nodeEnv = process.env.NODE_ENV; const nxBuild = process.env.NX_BUILD; const nxApi = process.env.NX_API; const nxWsBase = process.env.NX_WS_BASE; const nxWsEnvLocal = process.env.NX_WS_ENV_LOCAL; const nxWsLocalEnv = process.env.NX_WS_LOCAL_ENV; const nxAppBase = process.env.NX_APP_BASE; const nxAppEnvLocal = process.env.NX_APP_ENV_LOCAL; const nxAppLocalEnv = process.env.NX_APP_LOCAL_ENV; const nxSharedEnv = process.env.NX_SHARED_ENV; `; runCLI( `generate @nx/web:app ${appName} --bundler=webpack --no-interactive --compiler=babel` ); setMaxWorkers(join('apps', appName, 'project.json')); const content = readFile(main); updateFile(main, `${newCode}\n${content}`); const appName2 = uniq('app'); updateFile( `apps/${appName2}/.env`, 'NX_APP_BASE=app2-base\nNX_SHARED_ENV=shared2-in-app-base' ); updateFile( `apps/${appName2}/.env.local`, 'NX_APP_ENV_LOCAL=app2-env-local\nNX_SHARED_ENV=shared2-in-app-env-local' ); updateFile( `apps/${appName2}/.local.env`, 'NX_APP_LOCAL_ENV=app2-local-env\nNX_SHARED_ENV=shared2-in-app-local-env' ); const main2 = `apps/${appName2}/src/main.ts`; const newCode2 = `const envVars = [process.env.NODE_ENV, process.env.NX_BUILD, process.env.NX_API, process.env.NX_WS_BASE, process.env.NX_WS_ENV_LOCAL, process.env.NX_WS_LOCAL_ENV, process.env.NX_APP_BASE, process.env.NX_APP_ENV_LOCAL, process.env.NX_APP_LOCAL_ENV, process.env.NX_SHARED_ENV];`; runCLI( `generate @nx/web:app ${appName2} --bundler=webpack --no-interactive --compiler=babel` ); setMaxWorkers(join('apps', appName2, 'project.json')); const content2 = readFile(main2); updateFile(main2, `${newCode2}\n${content2}`); runCLI( `run-many --target build --outputHashing=none --optimization=false`, { env: { NODE_ENV: 'test', NX_BUILD: '52', NX_API: 'QA', }, } ); expect(readFile(`dist/apps/${appName}/main.js`)).toContain( 'const envVars = ["test", "52", "QA", "ws-base", "ws-env-local", "ws-local-env", "app-base", "app-env-local", "app-local-env", "shared-in-app-env-local"];' ); expect(readFile(`dist/apps/${appName2}/main.js`)).toContain( 'const envVars = ["test", "52", "QA", "ws-base", "ws-env-local", "ws-local-env", "app2-base", "app2-env-local", "app2-local-env", "shared2-in-app-env-local"];' ); }); }); describe('Build Options', () => { it('should inject/bundle external scripts and styles', async () => { newProject(); const appName = uniq('app'); runCLI( `generate @nx/web:app ${appName} --bundler=webpack --no-interactive` ); setMaxWorkers(join('apps', appName, 'project.json')); const srcPath = `apps/${appName}/src`; const fooCss = `${srcPath}/foo.css`; const barCss = `${srcPath}/bar.css`; const fooJs = `${srcPath}/foo.js`; const barJs = `${srcPath}/bar.js`; const fooCssContent = `/* ${uniq('foo')} */`; const barCssContent = `/* ${uniq('bar')} */`; const fooJsContent = `/* ${uniq('foo')} */`; const barJsContent = `/* ${uniq('bar')} */`; createFile(fooCss); createFile(barCss); createFile(fooJs); createFile(barJs); // createFile could not create a file with content updateFile(fooCss, fooCssContent); updateFile(barCss, barCssContent); updateFile(fooJs, fooJsContent); updateFile(barJs, barJsContent); const barScriptsBundleName = 'bar-scripts'; const barStylesBundleName = 'bar-styles'; updateJson(join('apps', appName, 'project.json'), (config) => { const buildOptions = config.targets.build.options; buildOptions.scripts = [ { input: fooJs, inject: true, }, { input: barJs, inject: false, bundleName: barScriptsBundleName, }, ]; buildOptions.styles = [ { input: fooCss, inject: true, }, { input: barCss, inject: false, bundleName: barStylesBundleName, }, ]; return config; }); runCLI(`build ${appName} --outputHashing none --optimization false`); const distPath = `dist/apps/${appName}`; const scripts = readFile(`${distPath}/scripts.js`); const styles = readFile(`${distPath}/styles.css`); const barScripts = readFile(`${distPath}/${barScriptsBundleName}.js`); const barStyles = readFile(`${distPath}/${barStylesBundleName}.css`); expect(scripts).toContain(fooJsContent); expect(scripts).not.toContain(barJsContent); expect(barScripts).toContain(barJsContent); expect(styles).toContain(fooCssContent); expect(styles).not.toContain(barCssContent); expect(barStyles).toContain(barCssContent); }); }); describe('index.html interpolation', () => { test('should interpolate environment variables', async () => { const appName = uniq('app'); runCLI( `generate @nx/web:app ${appName} --bundler=webpack --no-interactive` ); setMaxWorkers(join('apps', appName, 'project.json')); const srcPath = `apps/${appName}/src`; const indexPath = `${srcPath}/index.html`; const indexContent = `<!DOCTYPE html> <html lang='en'> <head> <meta charset='utf-8' /> <title>BestReactApp</title> <base href='/' /> <meta name='viewport' content='width=device-width, initial-scale=1' /> <link rel='icon' type='image/x-icon' href='favicon.ico' /> </head> <body> <div id='root'></div> <div>Nx Variable: %NX_VARIABLE%</div> <div>Some other variable: %SOME_OTHER_VARIABLE%</div> <div>Deploy Url: %DEPLOY_URL%</div> </body> </html> `; const envFilePath = `apps/${appName}/.env`; const envFileContents = ` NX_VARIABLE=foo SOME_OTHER_VARIABLE=bar }`; createFile(envFilePath); // createFile could not create a file with content updateFile(envFilePath, envFileContents); updateFile(indexPath, indexContent); updateJson(join('apps', appName, 'project.json'), (config) => { const buildOptions = config.targets.build.options; buildOptions.deployUrl = 'baz'; return config; }); runCLI(`build ${appName}`); const distPath = `dist/apps/${appName}`; const resultIndexContents = readFile(`${distPath}/index.html`); expect(resultIndexContents).toMatch(/<div>Nx Variable: foo<\/div>/); expect(resultIndexContents).toMatch(/<div>Nx Variable: foo<\/div>/); expect(resultIndexContents).toMatch(/ <div>Nx Variable: foo<\/div>/); }); });
2,093
0
petrpan-code/nrwl/nx/e2e/webpack
petrpan-code/nrwl/nx/e2e/webpack/src/webpack.test.ts
import { cleanupProject, newProject, packageInstall, rmDist, runCLI, runCommand, uniq, updateFile, updateJson, } from '@nx/e2e/utils'; import { join } from 'path'; describe('Webpack Plugin', () => { beforeAll(() => newProject()); afterAll(() => cleanupProject()); it('should be able to setup project to build node programs with webpack and different compilers', async () => { const myPkg = uniq('my-pkg'); runCLI(`generate @nx/js:lib ${myPkg} --bundler=none`); updateFile(`libs/${myPkg}/src/index.ts`, `console.log('Hello');\n`); runCLI( `generate @nx/webpack:configuration ${myPkg} --target=node --tsConfig=libs/${myPkg}/tsconfig.lib.json --main=libs/${myPkg}/src/index.ts` ); // Test `scriptType` later during during. updateFile( `libs/${myPkg}/webpack.config.js`, ` const { composePlugins, withNx } = require('@nx/webpack'); module.exports = composePlugins(withNx(), (config) => { console.log('scriptType is ' + config.output.scriptType); return config; }); ` ); rmDist(); const buildOutput = runCLI(`build ${myPkg}`); // Ensure scriptType is not set if we're in Node (it only applies to Web). expect(buildOutput).toContain('scriptType is undefined'); let output = runCommand(`node dist/libs/${myPkg}/main.js`); expect(output).toMatch(/Hello/); expect(output).not.toMatch(/Conflicting/); expect(output).not.toMatch(/process.env.NODE_ENV/); updateJson(join('libs', myPkg, 'project.json'), (config) => { delete config.targets.build; return config; }); // swc runCLI( `generate @nx/webpack:configuration ${myPkg} --target=node --tsConfig=libs/${myPkg}/tsconfig.lib.json --main=libs/${myPkg}/src/index.ts --compiler=swc` ); rmDist(); runCLI(`build ${myPkg}`); output = runCommand(`node dist/libs/${myPkg}/main.js`); expect(output).toMatch(/Hello/); updateJson(join('libs', myPkg, 'project.json'), (config) => { delete config.targets.build; return config; }); // tsc runCLI( `generate @nx/webpack:configuration ${myPkg} --target=node --tsConfig=libs/${myPkg}/tsconfig.lib.json --main=libs/${myPkg}/src/index.ts --compiler=tsc` ); rmDist(); runCLI(`build ${myPkg}`); output = runCommand(`node dist/libs/${myPkg}/main.js`); expect(output).toMatch(/Hello/); }, 500000); it('should use either BABEL_ENV or NODE_ENV value for Babel environment configuration', async () => { const myPkg = uniq('my-pkg'); runCLI(`generate @nx/js:lib ${myPkg} --bundler=none`); updateFile(`libs/${myPkg}/src/index.ts`, `console.log('Hello');\n`); runCLI( `generate @nx/webpack:configuration ${myPkg} --target=node --compiler=babel --tsConfig=libs/${myPkg}/tsconfig.lib.json --main=libs/${myPkg}/src/index.ts` ); updateFile( `libs/${myPkg}/.babelrc`, `{ 'presets': ['@nx/js/babel', './custom-preset'] } ` ); updateFile( `libs/${myPkg}/custom-preset.js`, ` module.exports = function(api, opts) { console.log('Babel env is ' + api.env()); return opts; } ` ); let output = runCLI(`build ${myPkg}`, { env: { NODE_ENV: 'nodeEnv', BABEL_ENV: 'babelEnv', }, }); expect(output).toContain('Babel env is babelEnv'); }, 500_000); it('should be able to build with NxWebpackPlugin and a standard webpack config file', () => { const appName = uniq('app'); runCLI(`generate @nx/web:app ${appName} --bundler webpack`); updateFile(`apps/${appName}/src/main.ts`, `console.log('Hello');\n`); updateFile( `apps/${appName}/webpack.config.js`, ` const path = require('path'); const { NxWebpackPlugin } = require('@nx/webpack'); module.exports = { target: 'node', output: { path: path.join(__dirname, '../../dist/${appName}') }, plugins: [ new NxWebpackPlugin() ] };` ); runCLI(`build ${appName} --outputHashing none`); let output = runCommand(`node dist/${appName}/main.js`); expect(output).toMatch(/Hello/); }, 500_000); // Issue: https://github.com/nrwl/nx/issues/20179 it('should allow main/styles entries to be spread within composePlugins() function (#20179)', () => { const appName = uniq('app'); runCLI(`generate @nx/web:app ${appName} --bundler webpack`); updateFile(`apps/${appName}/src/main.ts`, `console.log('Hello');\n`); updateFile( `apps/${appName}/webpack.config.js`, ` const { composePlugins, withNx, withWeb } = require('@nx/webpack'); module.exports = composePlugins(withNx(), withWeb(), (config) => { return { ...config, entry: { main: [...config.entry.main], styles: [...config.entry.styles], } }; }); ` ); expect(() => { runCLI(`build ${appName} --outputHashing none`); }).not.toThrow(); }); });
2,098
0
petrpan-code/nrwl/nx/e2e/workspace-create-npm
petrpan-code/nrwl/nx/e2e/workspace-create-npm/src/create-nx-workspace-npm.test.ts
import { checkFilesExist, cleanupProject, getSelectedPackageManager, packageInstall, readJson, runCLI, runCommand, runCreateWorkspace, uniq, } from '@nx/e2e/utils'; describe('create-nx-workspace --preset=npm', () => { const wsName = uniq('npm'); let orginalGlobCache; beforeAll(() => { orginalGlobCache = process.env.NX_PROJECT_GLOB_CACHE; // glob cache is causing previous projects to show in Workspace for maxWorkers overrides // which fails due to files no longer being available process.env.NX_PROJECT_GLOB_CACHE = 'false'; runCreateWorkspace(wsName, { preset: 'npm', packageManager: getSelectedPackageManager(), }); }); afterEach(() => { // cleanup previous projects runCommand(`rm -rf packages/** tsconfig.base.json`); }); afterAll(() => { process.env.NX_PROJECT_GLOB_CACHE = orginalGlobCache; cleanupProject({ skipReset: true }); }); it('should setup package-based workspace', () => { const packageJson = readJson('package.json'); expect(packageJson.dependencies).toEqual({}); if (getSelectedPackageManager() === 'pnpm') { checkFilesExist('pnpm-workspace.yaml'); } else { expect(packageJson.workspaces).toEqual(['packages/*']); } }); it('should add angular application', () => { packageInstall('@nx/angular', wsName); const appName = uniq('my-app'); expect(() => { runCLI( `generate @nx/angular:app ${appName} --projectNameAndRootFormat as-provided --no-interactive` ); }).not.toThrowError(); checkFilesExist('tsconfig.base.json'); }, 1_000_000); it('should add angular library', () => { packageInstall('@nx/angular', wsName); const libName = uniq('lib'); expect(() => { runCLI( `generate @nx/angular:lib ${libName} --directory packages/${libName} --projectNameAndRootFormat as-provided --no-interactive` ); }).not.toThrowError(); checkFilesExist('tsconfig.base.json'); const tsconfig = readJson(`tsconfig.base.json`); expect(tsconfig.compilerOptions.paths).toEqual({ [libName]: [`packages/${libName}/src/index.ts`], }); }, 1_000_000); it('should add js library', () => { packageInstall('@nx/js', wsName); const libName = uniq('lib'); expect(() => runCLI( `generate @nx/js:library ${libName} --directory packages/${libName} --projectNameAndRootFormat as-provided --no-interactive` ) ).not.toThrowError(); checkFilesExist('tsconfig.base.json'); const tsconfig = readJson(`tsconfig.base.json`); expect(tsconfig.compilerOptions.paths).toEqual({ [libName]: [`packages/${libName}/src/index.ts`], }); }); it('should add web application', () => { packageInstall('@nx/web', wsName); const appName = uniq('my-app'); expect(() => runCLI( `generate @nx/web:app ${appName} --projectNameAndRootFormat as-provided --no-interactive` ) ).not.toThrowError(); checkFilesExist('tsconfig.base.json'); }); it('should add react application', () => { packageInstall('@nx/react', wsName); const appName = uniq('my-app'); expect(() => { runCLI( `generate @nx/react:app ${appName} --projectNameAndRootFormat as-provided --no-interactive` ); }).not.toThrowError(); checkFilesExist('tsconfig.base.json'); }); it('should add react library', () => { packageInstall('@nx/react', wsName); const libName = uniq('lib'); expect(() => { runCLI( `generate @nx/react:lib ${libName} --directory packages/${libName} --projectNameAndRootFormat as-provided --no-interactive` ); }).not.toThrowError(); checkFilesExist('tsconfig.base.json'); const tsconfig = readJson(`tsconfig.base.json`); expect(tsconfig.compilerOptions.paths).toEqual({ [libName]: [`packages/${libName}/src/index.ts`], }); }); it('should add next application', () => { packageInstall('@nx/next', wsName); const appName = uniq('my-app'); expect(() => { runCLI( `generate @nx/next:app ${appName} --projectNameAndRootFormat as-provided --no-interactive` ); }).not.toThrowError(); checkFilesExist('tsconfig.base.json'); }); it('should add next library', () => { packageInstall('@nx/next', wsName); const libName = uniq('lib'); expect(() => { runCLI( `generate @nx/next:lib ${libName} --directory packages/${libName} --projectNameAndRootFormat as-provided --no-interactive` ); }).not.toThrowError(); checkFilesExist('tsconfig.base.json'); const tsconfig = readJson(`tsconfig.base.json`); expect(tsconfig.compilerOptions.paths).toEqual({ [libName]: [`packages/${libName}/src/index.ts`], [`${libName}/server`]: [`packages/${libName}/src/server.ts`], }); }); it('should add react-native application', () => { packageInstall('@nx/react-native', wsName); const appName = uniq('my-app'); expect(() => { runCLI( `generate @nx/react-native:app ${appName} --install=false --projectNameAndRootFormat as-provided --no-interactive` ); }).not.toThrowError(); checkFilesExist('tsconfig.base.json'); }); it('should add react-native library', () => { packageInstall('@nx/react-native', wsName); const libName = uniq('lib'); expect(() => { runCLI( `generate @nx/react-native:lib ${libName} --directory packages/${libName} --projectNameAndRootFormat as-provided --no-interactive` ); }).not.toThrowError(); checkFilesExist('tsconfig.base.json'); const tsconfig = readJson(`tsconfig.base.json`); expect(tsconfig.compilerOptions.paths).toEqual({ [libName]: [`packages/${libName}/src/index.ts`], }); }); it('should add node application', () => { packageInstall('@nx/node', wsName); const appName = uniq('my-app'); expect(() => { runCLI( `generate @nx/node:app ${appName} --projectNameAndRootFormat as-provided --no-interactive` ); }).not.toThrowError(); checkFilesExist('tsconfig.base.json'); }); it('should add node library', () => { packageInstall('@nx/node', wsName); const libName = uniq('lib'); expect(() => { runCLI( `generate @nx/node:lib ${libName} --directory packages/${libName} --projectNameAndRootFormat as-provided --no-interactive` ); }).not.toThrowError(); checkFilesExist('tsconfig.base.json'); const tsconfig = readJson(`tsconfig.base.json`); expect(tsconfig.compilerOptions.paths).toEqual({ [libName]: [`packages/${libName}/src/index.ts`], }); }); it('should add nest application', () => { packageInstall('@nx/nest', wsName); const appName = uniq('my-app'); expect(() => { runCLI( `generate @nx/nest:app ${appName} --projectNameAndRootFormat as-provided --no-interactive` ); }).not.toThrowError(); checkFilesExist('tsconfig.base.json'); }); it('should add nest library', () => { packageInstall('@nx/nest', wsName); const libName = uniq('lib'); expect(() => { runCLI( `generate @nx/nest:lib ${libName} --directory packages/${libName} --projectNameAndRootFormat as-provided --no-interactive` ); }).not.toThrowError(); checkFilesExist('tsconfig.base.json'); const tsconfig = readJson(`tsconfig.base.json`); expect(tsconfig.compilerOptions.paths).toEqual({ [libName]: [`packages/${libName}/src/index.ts`], }); }); it('should add express application', () => { packageInstall('@nx/express', wsName); const appName = uniq('my-app'); expect(() => { runCLI( `generate @nx/express:app ${appName} --projectNameAndRootFormat as-provided --no-interactive` ); }).not.toThrowError(); checkFilesExist('tsconfig.base.json'); }); });
2,103
0
petrpan-code/nrwl/nx/e2e/workspace-create
petrpan-code/nrwl/nx/e2e/workspace-create/src/create-nx-plugin.test.ts
import { checkFilesExist, getSelectedPackageManager, packageManagerLockFile, runCLI, uniq, runCreatePlugin, cleanupProject, } from '@nx/e2e/utils'; describe('create-nx-plugin', () => { const packageManager = getSelectedPackageManager() || 'pnpm'; afterEach(() => cleanupProject()); it('should be able to create a plugin repo build a plugin', () => { const pluginName = uniq('plugin'); const generatorName = uniq('generator'); const executorName = uniq('executor'); runCreatePlugin(pluginName, { packageManager, extraArgs: `--createPackageName=false`, }); checkFilesExist( 'package.json', packageManagerLockFile[packageManager], `project.json` ); runCLI(`build ${pluginName}`); checkFilesExist( `dist/${pluginName}/package.json`, `dist/${pluginName}/src/index.js` ); runCLI( `generate @nx/plugin:generator ${generatorName} --project=${pluginName}` ); runCLI( `generate @nx/plugin:executor ${executorName} --project=${pluginName}` ); runCLI(`build ${pluginName}`); checkFilesExist( `dist/${pluginName}/package.json`, `dist/${pluginName}/generators.json`, `dist/${pluginName}/executors.json` ); }); it('should be able to create a repo with create workspace cli', () => { const pluginName = uniq('plugin'); runCreatePlugin(pluginName, { packageManager, extraArgs: `--createPackageName=create-${pluginName}-package`, }); runCLI(`build ${pluginName}`); checkFilesExist( `dist/packages/${pluginName}/package.json`, `dist/packages/${pluginName}/generators.json`, `packages/${pluginName}-e2e/src/${pluginName}.spec.ts` ); runCLI(`build create-${pluginName}-package`); checkFilesExist(`dist/packages/create-${pluginName}-package/bin/index.js`); expect(() => runCLI(`e2e ${pluginName}-e2e`)).not.toThrow(); }); });
2,104
0
petrpan-code/nrwl/nx/e2e/workspace-create
petrpan-code/nrwl/nx/e2e/workspace-create/src/create-nx-workspace.test.ts
import { checkFilesDoNotExist, checkFilesExist, cleanupProject, e2eCwd, expectCodeIsFormatted, expectNoAngularDevkit, expectNoTsJestInJestConfig, getSelectedPackageManager, packageManagerLockFile, readJson, runCommand, runCreateWorkspace, uniq, } from '@nx/e2e/utils'; import { readFileSync } from 'fs'; import { existsSync, mkdirSync, rmSync } from 'fs-extra'; describe('create-nx-workspace', () => { const packageManager = getSelectedPackageManager() || 'pnpm'; afterEach(() => cleanupProject()); it('should create a workspace with a single angular app at the root without routing', () => { const wsName = uniq('angular'); runCreateWorkspace(wsName, { preset: 'angular-standalone', appName: wsName, style: 'css', packageManager, standaloneApi: false, routing: false, e2eTestRunner: 'none', bundler: 'webpack', ssr: false, }); checkFilesExist('package.json'); checkFilesExist('project.json'); checkFilesExist('src/app/app.module.ts'); checkFilesDoNotExist('src/app/app.routes.ts'); expectCodeIsFormatted(); }); it('should create a workspace with a single angular app at the root using standalone APIs', () => { const wsName = uniq('angular'); runCreateWorkspace(wsName, { preset: 'angular-standalone', appName: wsName, style: 'css', packageManager, standaloneApi: true, routing: true, e2eTestRunner: 'none', bundler: 'webpack', ssr: false, }); checkFilesExist('package.json'); checkFilesExist('project.json'); checkFilesExist('src/app/app.routes.ts'); checkFilesDoNotExist('src/app/app.module.ts'); expectCodeIsFormatted(); }); it('should create a workspace with a single react app with vite at the root', () => { const wsName = uniq('react'); runCreateWorkspace(wsName, { preset: 'react-standalone', appName: wsName, style: 'css', packageManager, bundler: 'vite', e2eTestRunner: 'none', }); checkFilesExist('package.json'); checkFilesExist('project.json'); checkFilesExist('vite.config.ts'); checkFilesDoNotExist('tsconfig.base.json'); expectCodeIsFormatted(); }); it('should create a workspace with a single react app with webpack and playwright at the root', () => { const wsName = uniq('react'); runCreateWorkspace(wsName, { preset: 'react-standalone', appName: wsName, style: 'css', packageManager, bundler: 'webpack', e2eTestRunner: 'playwright', }); checkFilesExist('package.json'); checkFilesExist('project.json'); checkFilesExist('webpack.config.js'); checkFilesDoNotExist('tsconfig.base.json'); expectCodeIsFormatted(); }); it('should be able to create an empty workspace built for apps', () => { const wsName = uniq('apps'); runCreateWorkspace(wsName, { preset: 'apps', packageManager, }); checkFilesExist('package.json', packageManagerLockFile[packageManager]); expectNoAngularDevkit(); }); it('should be able to create an empty workspace with npm capabilities', () => { const wsName = uniq('npm'); runCreateWorkspace(wsName, { preset: 'npm', packageManager, }); expectNoAngularDevkit(); checkFilesDoNotExist('tsconfig.base.json'); }); it('should be able to create an empty workspace with ts/js capabilities', () => { const wsName = uniq('ts'); runCreateWorkspace(wsName, { preset: 'ts', packageManager, }); expectNoAngularDevkit(); expectCodeIsFormatted(); }); it('should be able to create an angular workspace', () => { const wsName = uniq('angular'); const appName = uniq('app'); runCreateWorkspace(wsName, { preset: 'angular-monorepo', style: 'css', appName, packageManager, standaloneApi: false, routing: true, e2eTestRunner: 'none', bundler: 'webpack', ssr: false, }); expectCodeIsFormatted(); }); it('should fail correctly when preset errors', () => { // Using Angular Preset as the example here to test // It will error when npmScope is of form `<char>-<num>-<char>` // Due to a validation error Angular will throw. const wsName = uniq('angular-1-test'); const appName = uniq('app'); expect(() => runCreateWorkspace(wsName, { preset: 'angular-monorepo', style: 'css', appName, packageManager, standaloneApi: false, routing: false, e2eTestRunner: 'none', bundler: 'webpack', ssr: false, }) ).toThrow(); }); it('should be able to create a react workspace with webpack', () => { const wsName = uniq('react'); const appName = uniq('app'); runCreateWorkspace(wsName, { preset: 'react-monorepo', style: 'css', appName, packageManager, bundler: 'webpack', e2eTestRunner: 'none', }); expectNoAngularDevkit(); expectNoTsJestInJestConfig(appName); const packageJson = readJson('package.json'); expect(packageJson.devDependencies['@nx/webpack']).toBeDefined(); expectCodeIsFormatted(); }); it('should be able to create a react workspace with vite', () => { const wsName = uniq('react'); const appName = uniq('app'); runCreateWorkspace(wsName, { preset: 'react-monorepo', style: 'css', appName, packageManager, bundler: 'vite', e2eTestRunner: 'none', }); expectNoAngularDevkit(); const packageJson = readJson('package.json'); expect(packageJson.devDependencies['@nx/webpack']).not.toBeDefined(); expect(packageJson.devDependencies['@nx/vite']).toBeDefined(); expectCodeIsFormatted(); }); it('should be able to create an next workspace', () => { const wsName = uniq('next'); const appName = uniq('app'); runCreateWorkspace(wsName, { preset: 'next', style: 'css', appName, nextAppDir: false, packageManager, e2eTestRunner: 'none', }); checkFilesExist(`apps/${appName}/pages/index.tsx`); expectNoAngularDevkit(); expectCodeIsFormatted(); }); it('should be able to create a nextjs standalone workspace using app router', () => { const wsName = uniq('next'); const appName = uniq('app'); runCreateWorkspace(wsName, { preset: 'nextjs-standalone', style: 'css', nextAppDir: true, appName, packageManager, e2eTestRunner: 'none', }); checkFilesExist('app/page.tsx'); expectNoAngularDevkit(); expectCodeIsFormatted(); }); it('should be able to create a nextjs standalone workspace using pages router', () => { const wsName = uniq('next'); const appName = uniq('app'); runCreateWorkspace(wsName, { preset: 'nextjs-standalone', style: 'css', nextAppDir: false, appName, packageManager, e2eTestRunner: 'none', }); checkFilesExist('pages/index.tsx'); expectNoAngularDevkit(); expectCodeIsFormatted(); }); it('should be able to create an web-components workspace', () => { const wsName = uniq('web-components'); const appName = uniq('app'); runCreateWorkspace(wsName, { preset: 'web-components', style: 'css', appName, packageManager, }); expectNoAngularDevkit(); expectCodeIsFormatted(); }); it('should be able to create an express workspace', () => { const wsName = uniq('express'); const appName = uniq('app'); runCreateWorkspace(wsName, { preset: 'express', docker: false, appName, packageManager, }); expectNoAngularDevkit(); expectCodeIsFormatted(); }); it('should be able to create react-native workspace', () => { const wsName = uniq('react-native'); const appName = uniq('app'); runCreateWorkspace(wsName, { preset: 'react-native', appName, packageManager: 'npm', }); expectNoAngularDevkit(); expectCodeIsFormatted(); }); it('should be able to create an expo workspace', () => { const wsName = uniq('expo'); const appName = uniq('app'); runCreateWorkspace(wsName, { preset: 'expo', appName, packageManager: 'npm', }); expectNoAngularDevkit(); expectCodeIsFormatted(); }); it('should be able to create a workspace with a custom base branch and HEAD', () => { const wsName = uniq('branch'); runCreateWorkspace(wsName, { preset: 'apps', base: 'main', packageManager, }); }); it('should be able to create a workspace with custom commit information', () => { const wsName = uniq('branch'); runCreateWorkspace(wsName, { preset: 'apps', extraArgs: '--commit.name="John Doe" --commit.email="[email protected]" --commit.message="Custom commit message!"', packageManager, }); }); it('should be able to create a nest workspace', () => { const wsName = uniq('nest'); const appName = uniq('app'); runCreateWorkspace(wsName, { preset: 'nest', docker: false, appName, packageManager, }); expectCodeIsFormatted(); }); it('should respect package manager preference', () => { const wsName = uniq('pm'); process.env.YARN_REGISTRY = `http://localhost:4872`; process.env.SELECTED_PM = 'npm'; runCreateWorkspace(wsName, { preset: 'apps', packageManager: 'npm', }); checkFilesDoNotExist('yarn.lock'); checkFilesExist('package-lock.json'); process.env.SELECTED_PM = packageManager; }); it('should return error when ci workflow is selected but no cloud is set up', () => { const wsName = uniq('github'); runCreateWorkspace(wsName, { preset: 'apps', packageManager, ci: 'circleci', }); checkFilesExist('package.json'); checkFilesDoNotExist('.circleci/config.yml'); }); describe('Use detected package manager', () => { function setupProject(envPm: 'npm' | 'yarn' | 'pnpm') { process.env.SELECTED_PM = envPm; runCreateWorkspace(uniq('pm'), { preset: 'apps', packageManager: envPm, useDetectedPm: true, }); } if (packageManager === 'npm') { it('should use npm when invoked with npx', () => { setupProject('npm'); checkFilesExist(packageManagerLockFile['npm']); checkFilesDoNotExist( packageManagerLockFile['yarn'], packageManagerLockFile['pnpm'] ); process.env.SELECTED_PM = packageManager; }, 90000); } if (packageManager === 'pnpm') { it('should use pnpm when invoked with pnpx', () => { setupProject('pnpm'); checkFilesExist(packageManagerLockFile['pnpm']); checkFilesDoNotExist( packageManagerLockFile['yarn'], packageManagerLockFile['npm'] ); process.env.SELECTED_PM = packageManager; }, 90000); } // skipping due to packageManagerCommand for createWorkspace not using yarn create nx-workspace if (packageManager === 'yarn') { xit('should use yarn when invoked with yarn create', () => { setupProject('yarn'); checkFilesExist(packageManagerLockFile['yarn']); checkFilesDoNotExist( packageManagerLockFile['pnpm'], packageManagerLockFile['npm'] ); process.env.SELECTED_PM = packageManager; }, 90000); } }); it('should create a workspace with a single vue app at the root', () => { const wsName = uniq('vue'); runCreateWorkspace(wsName, { preset: 'vue-standalone', appName: wsName, style: 'css', packageManager, e2eTestRunner: 'none', }); checkFilesExist('package.json'); checkFilesExist('project.json'); checkFilesExist('index.html'); checkFilesExist('src/main.ts'); checkFilesExist('src/app/App.vue'); expectCodeIsFormatted(); }); it('should be able to create an vue monorepo', () => { const wsName = uniq('vue'); const appName = uniq('app'); runCreateWorkspace(wsName, { preset: 'vue-monorepo', appName, style: 'css', packageManager, e2eTestRunner: 'none', }); expectCodeIsFormatted(); }); }); describe('create-nx-workspace parent folder', () => { const tmpDir = `${e2eCwd}/${uniq('with space')}`; const wsName = uniq('parent'); const packageManager = getSelectedPackageManager() || 'pnpm'; afterEach(() => cleanupProject({ cwd: `${tmpDir}/${wsName}` })); it('should handle spaces in workspace path', () => { mkdirSync(tmpDir, { recursive: true }); runCreateWorkspace(wsName, { preset: 'apps', packageManager, cwd: tmpDir, }); expect(existsSync(`${tmpDir}/${wsName}/package.json`)).toBeTruthy(); }); }); describe('create-nx-workspace yarn berry', () => { const tmpDir = `${e2eCwd}/${uniq('yarn-berry')}`; let wsName: string; let yarnVersion: string; beforeAll(() => { mkdirSync(tmpDir, { recursive: true }); runCommand('corepack prepare [email protected] --activate', { cwd: tmpDir }); runCommand('yarn set version 3.6.1', { cwd: tmpDir }); yarnVersion = runCommand('yarn --version', { cwd: tmpDir }).trim(); // previous command creates a package.json file which we don't want rmSync(`${tmpDir}/package.json`); process.env.YARN_ENABLE_IMMUTABLE_INSTALLS = 'false'; }); afterEach(() => cleanupProject({ cwd: `${tmpDir}/${wsName}` })); it('should create a workspace with yarn berry', () => { wsName = uniq('apps'); runCreateWorkspace(wsName, { preset: 'apps', packageManager: 'yarn', cwd: tmpDir, }); expect(existsSync(`${tmpDir}/${wsName}/.yarnrc.yml`)).toBeTruthy(); expect( readFileSync(`${tmpDir}/${wsName}/.yarnrc.yml`, { encoding: 'utf-8' }) ).toMatchInlineSnapshot(` "nodeLinker: node-modules yarnPath: .yarn/releases/yarn-${yarnVersion}.cjs " `); }); it('should create a js workspace with yarn berry', () => { wsName = uniq('ts'); runCreateWorkspace(wsName, { preset: 'ts', packageManager: 'yarn', cwd: tmpDir, }); expect(existsSync(`${tmpDir}/${wsName}/.yarnrc.yml`)).toBeTruthy(); expect( readFileSync(`${tmpDir}/${wsName}/.yarnrc.yml`, { encoding: 'utf-8' }) ).toMatchInlineSnapshot(` "nodeLinker: node-modules yarnPath: .yarn/releases/yarn-${yarnVersion}.cjs " `); }); });
3,183
0
petrpan-code/nrwl/nx/packages/angular/src/generators
petrpan-code/nrwl/nx/packages/angular/src/generators/component-test/component-test.ts
import { assertMinimumCypressVersion } from '@nx/cypress/src/utils/cypress-version'; import { generateFiles, joinPathFragments, readProjectConfiguration, Tree, } from '@nx/devkit'; import { getArgsDefaultValue, getComponentProps, } from '../utils/storybook-ast/storybook-inputs'; import { ComponentTestSchema } from './schema'; export function componentTestGenerator( tree: Tree, options: ComponentTestSchema ) { assertMinimumCypressVersion(10); const { root } = readProjectConfiguration(tree, options.project); const componentDirPath = joinPathFragments(root, options.componentDir); const componentFilePath = joinPathFragments( componentDirPath, `${options.componentFileName}.ts` ); const componentTestFilePath = joinPathFragments( componentDirPath, `${options.componentFileName}.cy.ts` ); if (tree.exists(componentFilePath) && !tree.exists(componentTestFilePath)) { const props = getComponentProps( tree, componentFilePath, getArgsDefaultValue, false ); generateFiles( tree, joinPathFragments(__dirname, 'files'), componentDirPath, { componentName: options.componentName, componentFileName: options.componentFileName.startsWith('./') ? options.componentFileName.slice(2) : options.componentFileName, props: props.filter((p) => typeof p.defaultValue !== 'undefined'), tpl: '', } ); } } export default componentTestGenerator;
4,871
0
petrpan-code/nrwl/nx/packages/nuxt/src/generators/application
petrpan-code/nrwl/nx/packages/nuxt/src/generators/application/lib/add-vitest.ts
import { Tree, addDependenciesToPackageJson, joinPathFragments, readProjectConfiguration, updateProjectConfiguration, writeJson, } from '@nx/devkit'; import { NormalizedSchema } from '../schema'; import { happyDomVersion, nuxtVitestVersion, nxVersion, vitestVersion, } from '../../../utils/versions'; export function addVitest( tree: Tree, options: NormalizedSchema, projectRoot: string, projectOffsetFromRoot: string ) { addDependenciesToPackageJson( tree, {}, { '@nx/vite': nxVersion, '@vitest/coverage-c8': vitestVersion, '@vitest/ui': vitestVersion, vitest: vitestVersion, 'nuxt-vitest': nuxtVitestVersion, 'happy-dom': happyDomVersion, } ); const projectConfig = readProjectConfiguration(tree, options.name); projectConfig.targets['test'] = { executor: '@nx/vite:test', outputs: ['{options.reportsDirectory}'], options: { passWithNoTests: true, reportsDirectory: `${projectOffsetFromRoot}coverage/${projectRoot}`, config: `${projectRoot}/vitest.config.ts`, }, }; updateProjectConfiguration(tree, options.name, projectConfig); tree.write( joinPathFragments(projectRoot, 'vitest.config.ts'), ` import { defineVitestConfig } from 'nuxt-vitest/config'; import { nxViteTsPaths } from '@nx/vite/plugins/nx-tsconfig-paths.plugin'; export default defineVitestConfig({ plugins: [nxViteTsPaths()], test: { globals: true, cache: { dir: '${projectOffsetFromRoot}node_modules/.vitest', }, include: ['${projectRoot}/src/**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'], environment: 'nuxt', }, }); ` ); writeJson(tree, joinPathFragments(projectRoot, 'tsconfig.spec.json'), { extends: './tsconfig.json', compilerOptions: { outDir: `${projectOffsetFromRoot}dist/out-tsc`, types: ['vitest/globals', 'vitest/importMeta', 'vite/client', 'node'], composite: true, }, include: [ 'vitest.config.ts', 'src/**/*.test.ts', 'src/**/*.spec.ts', 'src/**/*.test.tsx', 'src/**/*.spec.tsx', 'src/**/*.test.js', 'src/**/*.spec.js', 'src/**/*.test.jsx', 'src/**/*.spec.jsx', 'src/**/*.d.ts', ], }); }
5,869
0
petrpan-code/nrwl/nx/packages/react/src/generators
petrpan-code/nrwl/nx/packages/react/src/generators/component-test/component-test.ts
import { ensurePackage, generateFiles, joinPathFragments, readProjectConfiguration, Tree, } from '@nx/devkit'; import { basename, dirname, extname, join, relative } from 'path'; import { findExportDeclarationsForJsx, getComponentNode, } from '../../utils/ast-utils'; import { getDefaultsForComponent } from '../../utils/component-props'; import { nxVersion } from '../../utils/versions'; import { ComponentTestSchema } from './schema'; import { ensureTypescript } from '@nx/js/src/utils/typescript/ensure-typescript'; let tsModule: typeof import('typescript'); export async function componentTestGenerator( tree: Tree, options: ComponentTestSchema ) { ensurePackage('@nx/cypress', nxVersion); const { assertMinimumCypressVersion } = await import( '@nx/cypress/src/utils/cypress-version' ); assertMinimumCypressVersion(10); // normalize any windows paths options.componentPath = options.componentPath.replace(/\\/g, '/'); const projectConfig = readProjectConfiguration(tree, options.project); const normalizedPath = options.componentPath.startsWith( projectConfig.sourceRoot ) ? relative(projectConfig.sourceRoot, options.componentPath) : options.componentPath; const componentPath = joinPathFragments( projectConfig.sourceRoot, normalizedPath ); if (tree.exists(componentPath)) { generateSpecsForComponents(tree, componentPath); } } function generateSpecsForComponents(tree: Tree, filePath: string) { if (!tsModule) { tsModule = ensureTypescript(); } const sourceFile = tsModule.createSourceFile( filePath, tree.read(filePath, 'utf-8'), tsModule.ScriptTarget.Latest, true ); const cmpNodes = findExportDeclarationsForJsx(sourceFile); const componentDir = dirname(filePath); const ext = extname(filePath); const fileName = basename(filePath, ext); if (tree.exists(joinPathFragments(componentDir, `${fileName}.cy${ext}`))) { return; } const defaultExport = getComponentNode(sourceFile); if (cmpNodes?.length) { const components = cmpNodes.map((cmp) => { const defaults = getDefaultsForComponent(sourceFile, cmp); const isDefaultExport = defaultExport ? (defaultExport as any).name.text === (cmp as any).name.text : false; return { isDefaultExport, props: [...defaults.props, ...defaults.argTypes], name: (cmp as any).name.text as string, typeName: defaults.propsTypeName, }; }); const namedImports = components .reduce((imports, cmp) => { if (cmp.typeName) { imports.push(cmp.typeName); } if (cmp.isDefaultExport) { return imports; } imports.push(cmp.name); return imports; }, []) .join(', '); const namedImportStatement = namedImports.length > 0 ? `, { ${namedImports} }` : ''; generateFiles(tree, join(__dirname, 'files'), componentDir, { fileName, components, importStatement: defaultExport ? `import ${ (defaultExport as any).name.text }${namedImportStatement} from './${fileName}'` : `import { ${namedImports} } from './${fileName}'`, ext, }); } } export default componentTestGenerator;
9,638
0
petrpan-code/jhipster/generator-jhipster/generators/vue/templates/src/main/webapp
petrpan-code/jhipster/generator-jhipster/generators/vue/templates/src/main/webapp/microfrontends/entities-menu.component-test.ts.ejs
import { defineComponent } from 'vue'; export default defineComponent({ compatConfig: { MODE: 3 }, name: 'EntitiesMenu', });
9,639
0
petrpan-code/jhipster/generator-jhipster/generators/vue/templates/src/main/webapp
petrpan-code/jhipster/generator-jhipster/generators/vue/templates/src/main/webapp/microfrontends/entities-router-test.ts.ejs
export default [];
656
0
petrpan-code/palantir/blueprint/packages/core
petrpan-code/palantir/blueprint/packages/core/test/tsconfig.json
{ "extends": "../src/tsconfig", "compilerOptions": { "declaration": false, "downlevelIteration": true, "lib": ["dom", "dom.iterable", "es5", "es2015.collection", "es2015.iterable", "es2015.promise"], "noEmit": true } }
779
0
petrpan-code/palantir/blueprint/packages/datetime
petrpan-code/palantir/blueprint/packages/datetime/test/tsconfig.json
{ "extends": "../src/tsconfig", "compilerOptions": { "declaration": false, "noEmit": true } }
842
0
petrpan-code/palantir/blueprint/packages/datetime2
petrpan-code/palantir/blueprint/packages/datetime2/test/tsconfig.json
{ "extends": "../src/tsconfig", "compilerOptions": { "declaration": false, "noEmit": true } }
1,140
0
petrpan-code/palantir/blueprint/packages/eslint-plugin
petrpan-code/palantir/blueprint/packages/eslint-plugin/test/classes-constants.test.ts
/* * Copyright 2019 Palantir Technologies, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // tslint:disable object-literal-sort-keys /* eslint-disable no-template-curly-in-string */ import { RuleTester } from "@typescript-eslint/rule-tester"; import dedent from "dedent"; import { classesConstantsRule } from "../src/rules/classes-constants"; const ruleTester = new RuleTester({ parser: require.resolve("@typescript-eslint/parser"), parserOptions: { ecmaFeatures: { jsx: true, }, sourceType: "module", }, }); ruleTester.run("classes-constants", classesConstantsRule, { invalid: [ // literal string { code: dedent`<div className="pt-fill" />`, errors: [{ messageId: "useBlueprintClasses", column: 16, line: 1 }], output: dedent` import { Classes } from "@blueprintjs/core"; <div className={Classes.FILL} /> `, }, // literal string with other classes { code: `<div className="pt-fill and-some-other-things" />`, errors: [{ messageId: "useBlueprintClasses", column: 16, line: 1 }], output: dedent` import { Classes } from "@blueprintjs/core"; <div className={${"`${Classes.FILL} and-some-other-things`"}} /> `, }, // literal string inside curly brackets { code: `<div className={"pt-fill"} />`, errors: [{ messageId: "useBlueprintClasses", column: 17, line: 1 }], output: dedent` import { Classes } from "@blueprintjs/core"; <div className={Classes.FILL} /> `, }, // literal string and other classes inside curly brackets { code: `<div className={"pt-fill and-some-other-things"} />`, errors: [{ messageId: "useBlueprintClasses", column: 17, line: 1 }], output: dedent` import { Classes } from "@blueprintjs/core"; <div className={${"`${Classes.FILL} and-some-other-things`"}} /> `, }, // template string { code: "<div className={`pt-fill`} />", errors: [{ messageId: "useBlueprintClasses", column: 17, line: 1 }], output: dedent` import { Classes } from "@blueprintjs/core"; <div className={Classes.FILL} /> `, }, // template string and other classes { code: "<div className={`pt-fill and-some-other-things`} />", errors: [{ messageId: "useBlueprintClasses", column: 17, line: 1 }], output: dedent` import { Classes } from "@blueprintjs/core"; <div className={${"`${Classes.FILL} and-some-other-things`"}} /> `, }, // function usage { code: `classNames("pt-fill");`, errors: [{ messageId: "useBlueprintClasses", column: 12, line: 1 }], output: dedent` import { Classes } from "@blueprintjs/core"; classNames(Classes.FILL); `, }, // function usage with literal string and preceding period { code: `myFunction(".pt-fill");`, errors: [{ messageId: "useBlueprintClasses", column: 12, line: 1 }], output: dedent` import { Classes } from "@blueprintjs/core"; myFunction(${"`.${Classes.FILL}`"}); `, }, // function usage literal string with preceding period and preceding class { code: `myFunction("my-class .pt-fill");`, errors: [{ messageId: "useBlueprintClasses", column: 12, line: 1 }], output: dedent` import { Classes } from "@blueprintjs/core"; myFunction(${"`my-class .${Classes.FILL}`"}); `, }, // function usage with template string and preceding period { code: "myFunction(`my-class .pt-fill`);", errors: [{ messageId: "useBlueprintClasses", column: 12, line: 1 }], output: dedent` import { Classes } from "@blueprintjs/core"; myFunction(${"`my-class .${Classes.FILL}`"}); `, }, // array index usage { code: `classNames["pt-fill"] = true;`, errors: [{ messageId: "useBlueprintClasses", column: 12, line: 1 }], output: dedent` import { Classes } from "@blueprintjs/core"; classNames[Classes.FILL] = true; `, }, // adding import to existing import { code: dedent` import { Dialog } from "@blueprintjs/core"; classNames["pt-fill"] = true; `, errors: [{ messageId: "useBlueprintClasses", column: 12, line: 3 }], output: dedent` import { Classes, Dialog } from "@blueprintjs/core"; classNames[Classes.FILL] = true; `, }, // adding import in alphabetical order { code: dedent` import { Something } from "@a/somewhere"; import { SomethingElse } from "somewhere"; classNames["pt-fill"] = true; `, errors: [{ messageId: "useBlueprintClasses", column: 12, line: 4 }], output: dedent` import { Something } from "@a/somewhere"; import { Classes } from "@blueprintjs/core"; import { SomethingElse } from "somewhere"; classNames[Classes.FILL] = true; `, }, ], valid: [ "<div className={Classes.FILL} />", '<div className="my-own-class" />', '<div className={"my-own-class"} />', "<div className={`my-own-class`} />", // it should not touch icons as theyre handled by a different rule '<div className="pt-icon-folder-open" />', // don't flag strings in export/import statements 'import { test } from "packagewithpt-thatshouldnterror";', 'export { test } from "packagewithpt-thatshouldnterror";', // don't flag non applicable strings in function calls `myFunction("stringwithpt-thatshouldnt-error");`, "myFunction(`stringwithpt-thatshouldnt-error`);", ], });
1,141
0
petrpan-code/palantir/blueprint/packages/eslint-plugin
petrpan-code/palantir/blueprint/packages/eslint-plugin/test/html-components.test.ts
/* * Copyright 2019 Palantir Technologies, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { RuleTester } from "@typescript-eslint/rule-tester"; import dedent from "dedent"; import { htmlComponentsRule } from "../src/rules/html-components"; // tslint:disable object-literal-sort-keys const ruleTester = new RuleTester({ parser: require.resolve("@typescript-eslint/parser"), parserOptions: { ecmaFeatures: { jsx: true, }, sourceType: "module", }, }); ruleTester.run("html-components", htmlComponentsRule, { invalid: [ { code: "<h1 />", errors: [ { messageId: "useBlueprintComponents", column: 1, line: 1, data: { componentName: "H1" }, }, ], output: dedent` import { H1 } from "@blueprintjs/core"; <H1 /> `, }, { code: "<h1>Text</h1>", errors: [ { messageId: "useBlueprintComponents", column: 1, line: 1, data: { componentName: "H1" }, }, ], output: dedent` import { H1 } from "@blueprintjs/core"; <H1>Text</H1> `, }, { code: "<pre>block</pre>", errors: [ { messageId: "useBlueprintComponents", column: 1, line: 1, data: { componentName: "Pre" }, }, ], output: dedent` import { Pre } from "@blueprintjs/core"; <Pre>block</Pre> `, }, { code: "<table>table element</table>", errors: [ { messageId: "useBlueprintComponents", column: 1, line: 1, data: { componentName: "HTMLTable" }, }, ], output: dedent` import { HTMLTable } from "@blueprintjs/core"; <HTMLTable>table element</HTMLTable> `, }, ], valid: ["<div />", "<div></div>", "<H1 />"], });
1,142
0
petrpan-code/palantir/blueprint/packages/eslint-plugin
petrpan-code/palantir/blueprint/packages/eslint-plugin/test/icon-components.test.ts
/* * Copyright 2019 Palantir Technologies, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { RuleTester } from "@typescript-eslint/rule-tester"; import { iconComponentsRule, OPTION_COMPONENT, OPTION_LITERAL } from "../src/rules/icon-components"; // tslint:disable object-literal-sort-keys const ruleTester = new RuleTester({ parser: require.resolve("@typescript-eslint/parser"), parserOptions: { ecmaFeatures: { jsx: true, }, }, }); ruleTester.run("icon-components", iconComponentsRule, { invalid: [ { code: `<Button icon="tick" />`, errors: [ { messageId: OPTION_COMPONENT, column: 9, line: 1, data: { [OPTION_COMPONENT]: "<TickIcon />" }, }, ], output: `<Button icon={<TickIcon />} />`, }, { code: `<Button icon="tick" />`, errors: [ { messageId: OPTION_COMPONENT, column: 9, line: 1, data: { [OPTION_COMPONENT]: "<TickIcon />" }, }, ], options: [OPTION_COMPONENT], output: `<Button icon={<TickIcon />} />`, }, { code: `<Button icon={<TickIcon />} />`, errors: [ { messageId: OPTION_LITERAL, column: 9, line: 1, data: { [OPTION_LITERAL]: `"tick"` }, }, ], options: [OPTION_LITERAL], output: `<Button icon="tick" />`, }, ], valid: [ { code: `<Button icon="tick" />`, options: [OPTION_LITERAL], }, { code: `<Button icon={<TickIcon />} />`, options: [OPTION_COMPONENT], }, { code: `<InputGroup rightElement={<Button />} />`, options: [OPTION_LITERAL], }, ], });
1,143
0
petrpan-code/palantir/blueprint/packages/eslint-plugin
petrpan-code/palantir/blueprint/packages/eslint-plugin/test/no-deprecated-components.test.ts
/* * Copyright 2022 Palantir Technologies, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // tslint:disable object-literal-sort-keys /* eslint-disable no-template-curly-in-string */ import { RuleTester } from "@typescript-eslint/rule-tester"; import dedent from "dedent"; import { noDeprecatedComponentsRule } from "../src/rules/no-deprecated-components"; const ruleTester = new RuleTester({ parser: require.resolve("@typescript-eslint/parser"), parserOptions: { ecmaFeatures: { jsx: true, }, sourceType: "module", }, }); ruleTester.run("no-deprecated-components", noDeprecatedComponentsRule, { invalid: [], valid: [ { code: dedent` import { Button } from "@blueprintjs/core"; return <Button /> `, }, { code: dedent` import { OverflowList } from "@blueprintjs/core"; return <OverflowList /> `, }, { code: dedent` import { OverflowList } from "@blueprintjs/core"; export class MyList extends OverflowList {} `, }, { code: dedent` import * as BP from "@blueprintjs/core"; return <BP.Button /> `, }, { code: dedent` import { CollapsibleList } from "@blueprintjs/core"; return <CollapsibleList /> `, }, { code: dedent` import * as BP from "@blueprintjs/core"; return <BP.CollapsibleList /> `, }, { code: dedent` import { AbstractComponent } from "@blueprintjs/core"; export class MyClass extends AbstractComponent { } `, }, { code: dedent` import * as BP from "@blueprintjs/core"; export class MyClass extends BP.AbstractComponent { } class MyClass2 extends BP.AbstractComponent {} `, }, ], });
1,144
0
petrpan-code/palantir/blueprint/packages/eslint-plugin
petrpan-code/palantir/blueprint/packages/eslint-plugin/test/no-deprecated-core-components.test.ts
/* * Copyright 2022 Palantir Technologies, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // tslint:disable object-literal-sort-keys /* eslint-disable no-template-curly-in-string */ import { RuleTester } from "@typescript-eslint/rule-tester"; import dedent from "dedent"; import { noDeprecatedCoreComponentsRule } from "../src/rules/no-deprecated-components"; const ruleTester = new RuleTester({ parser: require.resolve("@typescript-eslint/parser"), parserOptions: { ecmaFeatures: { jsx: true, }, sourceType: "module", }, }); ruleTester.run("no-deprecated-core-components", noDeprecatedCoreComponentsRule, { // N.B. most other deprecated components are tested by no-deprecated-components.test.ts, this suite just tests // for more specific violations which involve certain deprecated props invalid: [], valid: [ { code: dedent` import { MenuItem } from "@blueprintjs/core"; return <MenuItem text="Open in new tab" icon="share" /> `, }, { code: dedent` import * as Blueprint from "@blueprintjs/core"; return <Blueprint.MenuItem text="Open in new tab" icon="share" /> `, }, { code: dedent` import { MenuItem } from "@blueprintjs/core"; return <MenuItem popoverProps={{ boundary: "window" }} /> `, }, { code: dedent` import * as Blueprint from "@blueprintjs/core"; return <Blueprint.MenuItem popoverProps={{ boundary: "window" }} /> `, }, ], });
1,145
0
petrpan-code/palantir/blueprint/packages/eslint-plugin
petrpan-code/palantir/blueprint/packages/eslint-plugin/test/no-deprecated-datetime-components.test.ts
/* * Copyright 2022 Palantir Technologies, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // tslint:disable object-literal-sort-keys /* eslint-disable no-template-curly-in-string */ import { RuleTester } from "@typescript-eslint/rule-tester"; import dedent from "dedent"; import { noDeprecatedDatetimeComponentsRule } from "../src/rules/no-deprecated-components"; const ruleTester = new RuleTester({ parser: require.resolve("@typescript-eslint/parser"), parserOptions: { ecmaFeatures: { jsx: true, }, sourceType: "module", }, }); ruleTester.run("no-deprecated-datetime-components", noDeprecatedDatetimeComponentsRule, { invalid: [ { code: dedent` import { DatePicker } from "@blueprintjs/datetime"; return <DatePicker />; `, errors: [ { messageId: "migration", data: { deprecatedComponentName: "DatePicker", newComponentName: "DatePicker3", }, }, ], }, ], valid: [ { code: dedent` import { DatePicker3 } from "@blueprintjs/datetime2"; return <DatePicker3 />; `, }, ], });
1,146
0
petrpan-code/palantir/blueprint/packages/eslint-plugin
petrpan-code/palantir/blueprint/packages/eslint-plugin/test/no-deprecated-datetime2-components.test.ts
/* * Copyright 2023 Palantir Technologies, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // tslint:disable object-literal-sort-keys /* eslint-disable no-template-curly-in-string */ import { RuleTester } from "@typescript-eslint/rule-tester"; import dedent from "dedent"; import { noDeprecatedDatetime2ComponentsRule } from "../src/rules/no-deprecated-components"; const ruleTester = new RuleTester({ parser: require.resolve("@typescript-eslint/parser"), parserOptions: { ecmaFeatures: { jsx: true, }, sourceType: "module", }, }); ruleTester.run("no-deprecated-datetime2-components", noDeprecatedDatetime2ComponentsRule, { invalid: [ { code: dedent` import { DateInput2 } from "@blueprintjs/datetime2"; return <DateInput2 />; `, errors: [ { messageId: "migration", data: { deprecatedComponentName: "DateInput2", newComponentName: "DateInput3", }, }, ], }, ], valid: [ { code: dedent` import { DateInput3 } from "@blueprintjs/datetime2"; return <DateInput3 />; `, }, ], });
1,147
0
petrpan-code/palantir/blueprint/packages/eslint-plugin
petrpan-code/palantir/blueprint/packages/eslint-plugin/test/no-deprecated-popover2-components.test.ts
/* * Copyright 2023 Palantir Technologies, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // tslint:disable object-literal-sort-keys /* eslint-disable no-template-curly-in-string */ import { RuleTester } from "@typescript-eslint/rule-tester"; import dedent from "dedent"; import { noDeprecatedPopover2ComponentsRule } from "../src/rules/no-deprecated-components"; const ruleTester = new RuleTester({ parser: require.resolve("@typescript-eslint/parser"), parserOptions: { ecmaFeatures: { jsx: true, }, sourceType: "module", }, }); ruleTester.run("no-deprecated-popover2-components", noDeprecatedPopover2ComponentsRule, { invalid: [ { code: dedent` import { Popover2 } from "@blueprintjs/popover2"; return <Popover2 />; `, errors: [ { messageId: "migrationToNewPackage", data: { deprecatedComponentName: "Popover2", newComponentName: "Popover", newPackageName: "@blueprintjs/core", }, }, ], }, ], valid: [ { code: dedent` import { Popover } from "@blueprintjs/core"; return <Popover />; `, }, ], });
1,148
0
petrpan-code/palantir/blueprint/packages/eslint-plugin
petrpan-code/palantir/blueprint/packages/eslint-plugin/test/no-deprecated-select-components.test.ts
/* * Copyright 2022 Palantir Technologies, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // tslint:disable object-literal-sort-keys /* eslint-disable no-template-curly-in-string */ import { RuleTester } from "@typescript-eslint/rule-tester"; import dedent from "dedent"; import { noDeprecatedSelectComponentsRule } from "../src/rules/no-deprecated-components"; const ruleTester = new RuleTester({ parser: require.resolve("@typescript-eslint/parser"), parserOptions: { ecmaFeatures: { jsx: true, }, sourceType: "module", }, }); ruleTester.run("no-deprecated-select-components", noDeprecatedSelectComponentsRule, { // N.B. most other deprecated components are tested by no-deprecated-components.test.ts, this suite just tests // for more specific violations which involve certain syntax invalid: [ { code: dedent` import { Select2 } from "@blueprintjs/select"; return <Select2<string> />; `, errors: [ { messageId: "migration", data: { deprecatedComponentName: "Select2", newComponentName: "Select", }, }, ], }, ], valid: [ { code: dedent` import { Select } from "@blueprintjs/select"; return <Select<string> />; `, }, { code: dedent` import { MultiSelect } from "@blueprintjs/select"; const MyMultiSelect = MultiSelect.ofType<any>(); `, }, ], });
1,149
0
petrpan-code/palantir/blueprint/packages/eslint-plugin
petrpan-code/palantir/blueprint/packages/eslint-plugin/test/no-deprecated-table-components.test.ts
/* * Copyright 2023 Palantir Technologies, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // tslint:disable object-literal-sort-keys /* eslint-disable no-template-curly-in-string */ import { RuleTester } from "@typescript-eslint/rule-tester"; import dedent from "dedent"; import { noDeprecatedTableComponentsRule } from "../src/rules/no-deprecated-components"; const ruleTester = new RuleTester({ parser: require.resolve("@typescript-eslint/parser"), parserOptions: { ecmaFeatures: { jsx: true, }, sourceType: "module", }, }); ruleTester.run("no-deprecated-table-components", noDeprecatedTableComponentsRule, { invalid: [ { code: dedent` import { JSONFormat2 } from "@blueprintjs/table"; return <JSONFormat2 />; `, errors: [ { messageId: "migration", data: { deprecatedComponentName: "JSONFormat2", newComponentName: "JSONFormat", }, }, ], }, ], valid: [ { code: dedent` import { JSONFormat } from "@blueprintjs/table"; return <JSONFormat />; `, }, ], });
1,150
0
petrpan-code/palantir/blueprint/packages/eslint-plugin
petrpan-code/palantir/blueprint/packages/eslint-plugin/test/no-deprecated-type-references.test.ts
/* * Copyright 2022 Palantir Technologies, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // tslint:disable object-literal-sort-keys /* eslint-disable no-template-curly-in-string */ import { RuleTester } from "@typescript-eslint/rule-tester"; import dedent from "dedent"; import { noDeprecatedTypeReferencesRule } from "../src/rules/no-deprecated-type-references"; const ruleTester = new RuleTester({ parser: require.resolve("@typescript-eslint/parser"), parserOptions: { ecmaFeatures: { jsx: true, }, sourceType: "module", }, }); ruleTester.run("no-deprecated-type-references", noDeprecatedTypeReferencesRule, { invalid: [ { code: dedent` import { IProps } from "@blueprintjs/core"; export interface MyInterface extends IProps { foo: string; } `, errors: [ { messageId: "migration", data: { deprecatedTypeName: "IProps", newTypeName: "Props" }, }, ], output: dedent` import { Props } from "@blueprintjs/core"; export interface MyInterface extends Props { foo: string; } `, }, { code: dedent` import * as Blueprint from "@blueprintjs/core"; export interface MyInterface extends Blueprint.IProps { foo: string; } `, errors: [ { messageId: "migration", data: { deprecatedTypeName: "IProps", newTypeName: "Props" }, }, ], output: dedent` import * as Blueprint from "@blueprintjs/core"; export interface MyInterface extends Blueprint.Props { foo: string; } `, }, { code: dedent` import { MenuItem } from "@blueprintjs/core"; import { IItemRendererProps } from "@blueprintjs/select"; export const defaultRenderMenuItem = (_item: any, { handleClick, modifiers }: IItemRendererProps) => { return <MenuItem {...modifiers} onClick={handleClick} />; }; `, errors: [ { messageId: "migration", data: { deprecatedTypeName: "IItemRendererProps", newTypeName: "ItemRendererProps" }, }, ], output: dedent` import { MenuItem } from "@blueprintjs/core"; import { ItemRendererProps } from "@blueprintjs/select"; export const defaultRenderMenuItem = (_item: any, { handleClick, modifiers }: ItemRendererProps) => { return <MenuItem {...modifiers} onClick={handleClick} />; }; `, }, // N.B. it is difficult to test fixes of multiple violations with ESLint's RuleTester, // see https://github.com/eslint/eslint/issues/11187#issuecomment-470990425 { code: dedent` import { ISelectProps } from "@blueprintjs/select"; const mySelectProps: ISelectProps = { items: [] }; `, errors: [ { messageId: "migration", data: { deprecatedTypeName: "ISelectProps", newTypeName: "SelectProps" }, }, ], output: dedent` import { SelectProps } from "@blueprintjs/select"; const mySelectProps: SelectProps = { items: [] }; `, }, // Ensure that multiple references/uses of the _same_ deprecated type are all fixed { code: dedent` import { ItemRenderer, IItemRendererProps } from "@blueprintjs/select"; const fooRenderer: ItemRenderer<any> = (item: any, props: IItemRendererProps) => { return "foo"; } const barRenderer: ItemRenderer<any> = (item: any, props: IItemRendererProps) => { return "bar"; } `, errors: [ { messageId: "migration", data: { deprecatedTypeName: "IItemRendererProps", newTypeName: "ItemRendererProps" }, }, { messageId: "migration", data: { deprecatedTypeName: "IItemRendererProps", newTypeName: "ItemRendererProps" }, }, ], output: dedent` import { ItemRenderer, ItemRendererProps } from "@blueprintjs/select"; const fooRenderer: ItemRenderer<any> = (item: any, props: ItemRendererProps) => { return "foo"; } const barRenderer: ItemRenderer<any> = (item: any, props: ItemRendererProps) => { return "bar"; } `, }, { code: dedent` import { Button, IButtonProps } from "@blueprintjs/core"; const ButtonAlias = (props: IButtonProps) => <Button {...props} />; interface MyButtonProps extends IButtonProps { type: string; } const MyButton = (props: MyButtonProps) => <Button {...props} />; `, errors: [ { messageId: "migration", data: { deprecatedTypeName: "IButtonProps", newTypeName: "ButtonProps" }, }, { messageId: "migration", data: { deprecatedTypeName: "IButtonProps", newTypeName: "ButtonProps" }, }, ], output: dedent` import { Button, ButtonProps } from "@blueprintjs/core"; const ButtonAlias = (props: ButtonProps) => <Button {...props} />; interface MyButtonProps extends ButtonProps { type: string; } const MyButton = (props: MyButtonProps) => <Button {...props} />; `, }, // dealing with name conflicts which require import aliases { code: dedent` import { IProps } from "@blueprintjs/core"; export interface Props extends IProps { foo: string; } `, errors: [ { messageId: "migration", data: { deprecatedTypeName: "IProps", newTypeName: "Props" }, }, ], output: dedent` import { Props as BlueprintProps } from "@blueprintjs/core"; export interface Props extends BlueprintProps { foo: string; } `, }, { code: dedent` import { IProps } from "@blueprintjs/core"; export namespace MyComponent { export interface Props extends IProps { foo: string; } } `, errors: [ { messageId: "migration", data: { deprecatedTypeName: "IProps", newTypeName: "Props" }, }, ], output: dedent` import { Props as BlueprintProps } from "@blueprintjs/core"; export namespace MyComponent { export interface Props extends BlueprintProps { foo: string; } } `, }, ], valid: [ { code: dedent` import { ButtonProps } from "@blueprintjs/core"; function MyButton(_props: ButtonProps) { return <button />; } `, }, ], });
1,152
0
petrpan-code/palantir/blueprint/packages/eslint-plugin
petrpan-code/palantir/blueprint/packages/eslint-plugin/test/tsconfig.json
{ "extends": "../../../config/tsconfig.node", "compilerOptions": { "lib": ["es2021"], "module": "commonjs", "noEmit": true, "skipLibCheck": true, "target": "es2021" } }
1,206
0
petrpan-code/palantir/blueprint/packages/icons
petrpan-code/palantir/blueprint/packages/icons/test/tsconfig.json
{ "extends": "../src/tsconfig", "compilerOptions": { "declaration": false, "noEmit": true } }
1,261
0
petrpan-code/palantir/blueprint/packages/node-build-scripts/src
petrpan-code/palantir/blueprint/packages/node-build-scripts/src/__tests__/cssVariables.test.ts
/** * Copyright 2023 Palantir Technologies, Inc. All rights reserved. */ import { describe, expect, test } from "@jest/globals"; import { readFileSync } from "node:fs"; import { dirname, join, resolve } from "node:path"; import { fileURLToPath } from "node:url"; import { generateLessVariables, generateScssVariables, getParsedVars } from "../cssVariables.mjs"; const __dirname = dirname(fileURLToPath(import.meta.url)); const FIXTURES_DIR = join(__dirname, "__fixtures__"); const INPUT_DIR = resolve(FIXTURES_DIR, "input"); const EXPECTED_DIR = resolve(FIXTURES_DIR, "expected"); describe("generateScssVariables", () => { test("produces expected output", async () => { const parsedInput = await getParsedVars(INPUT_DIR, ["_variables.scss"]); const actualVariables = await generateScssVariables(parsedInput, true); const expectedVariables = readFileSync(join(EXPECTED_DIR, "variables.scss"), { encoding: "utf8" }); expect(actualVariables).toStrictEqual(expectedVariables); }); }); describe("generateLessVariables", () => { test("produces expected output", async () => { const parsedInput = await getParsedVars(INPUT_DIR, ["_variables.scss"]); const actualVariables = await generateLessVariables(parsedInput); const expectedVariables = readFileSync(join(EXPECTED_DIR, "variables.less"), { encoding: "utf8" }); expect(actualVariables).toStrictEqual(expectedVariables); }); });
1,334
0
petrpan-code/palantir/blueprint/packages/select
petrpan-code/palantir/blueprint/packages/select/test/tsconfig.json
{ "extends": "../src/tsconfig", "compilerOptions": { "declaration": false, "noEmit": true } }
1,498
0
petrpan-code/palantir/blueprint/packages/table
petrpan-code/palantir/blueprint/packages/table/test/tsconfig.json
{ "extends": "../src/tsconfig", "compilerOptions": { "declaration": false, "noEmit": true } }
1,533
0
petrpan-code/palantir/blueprint/packages/tslint-config/test/rules/blueprint-classes-constants
petrpan-code/palantir/blueprint/packages/tslint-config/test/rules/blueprint-classes-constants/false/test.tsx.lint
<Button className="pt-large" /> classNames(Classes.BUTTON, "pt-intent-primary")
1,537
0
petrpan-code/palantir/blueprint/packages/tslint-config/test/rules/blueprint-classes-constants
petrpan-code/palantir/blueprint/packages/tslint-config/test/rules/blueprint-classes-constants/true/test.tsx.fix
import { Classes } from "@blueprintjs/core"; apt-get at 4pt-size `${Classes.LARGE} script-source apt-get` `script-source ${Classes.LARGE} apt-get` `${template} ${Classes.LARGE}` `${template} ${Classes.VERTICAL} ${Classes.FILL}` <Button className=`${Classes.LARGE} my-class` /> <Button className={Classes.MINIMAL} /> classNames(Classes.BUTTON, Classes.INTENT_PRIMARY) classNames(Classes.BUTTON, Classes.MINIMAL) <pt-popover> // angular directive
1,538
0
petrpan-code/palantir/blueprint/packages/tslint-config/test/rules/blueprint-classes-constants
petrpan-code/palantir/blueprint/packages/tslint-config/test/rules/blueprint-classes-constants/true/test.tsx.lint
apt-get at 4pt-size "script-source pt-large apt-get" ~~~~~~~~ [msg] `script-source pt-large apt-get` ~~~~~~~~ [msg] `${template} pt-large` ~~~~~~~~ [msg] `${template} pt-vertical bp3-fill` ~~~~~~~~~~~ [msg] <Button className="my-class pt-large" /> ~~~~~~~~ [msg] <Button className="bp3-minimal" /> ~~~~~~~~~~~ [msg] classNames(Classes.BUTTON, "pt-intent-primary") ~~~~~~~~~~~~~~~~~ [msg] classNames("bp3-button", "bp3-minimal") ~~~~~~~~~~ [msg] ~~~~~~~~~~~ [msg] <pt-popover> // angular directive [msg]: use Blueprint `Classes` constant instead of string literal
1,542
0
petrpan-code/palantir/blueprint/packages/tslint-config/test/rules/blueprint-html-components
petrpan-code/palantir/blueprint/packages/tslint-config/test/rules/blueprint-html-components/true/test.tsx.fix
import { Blockquote, Code, H1, H3, Pre } from "@blueprintjs/core"; <H3>Subtitle</H3> <Pre>block</Pre> <H1>Title</H1> <Code>code element</Code> <Blockquote />
1,543
0
petrpan-code/palantir/blueprint/packages/tslint-config/test/rules/blueprint-html-components
petrpan-code/palantir/blueprint/packages/tslint-config/test/rules/blueprint-html-components/true/test.tsx.lint
import { H3, Pre } from "@blueprintjs/core"; <H3>Subtitle</H3> <Pre>block</Pre> <h1>Title</h1> ~~ [err % ("H1")] <code>code element</code> ~~~~ [err % ("Code")] <blockquote /> ~~~~~~~~~~ [err % ("Blockquote")] [err]: use Blueprint <%s> component instead of JSX intrinsic element.
1,545
0
petrpan-code/palantir/blueprint/packages/tslint-config/test/rules/blueprint-icon-components
petrpan-code/palantir/blueprint/packages/tslint-config/test/rules/blueprint-icon-components/component/test.tsx.lint
<Button icon="tick" /> ~~~~~~ [err % ("<TickIcon />")] <Button icon={<TickIcon />} /> <InputGroup rightElement={<Button />} /> [err]: Replace icon literal with component: %s
1,547
0
petrpan-code/palantir/blueprint/packages/tslint-config/test/rules/blueprint-icon-components
petrpan-code/palantir/blueprint/packages/tslint-config/test/rules/blueprint-icon-components/false/test.tsx.lint
<Button icon="tick" /> <Button icon={<TickIcon />} /> <InputGroup rightElement={<Button />} />
1,549
0
petrpan-code/palantir/blueprint/packages/tslint-config/test/rules/blueprint-icon-components
petrpan-code/palantir/blueprint/packages/tslint-config/test/rules/blueprint-icon-components/literal/test.tsx.lint
<Button icon={<TickIcon />} /> ~~~~~~~~~~~~~~ [err % ('"tick"')] <Button icon="tick" /> <InputGroup rightElement={<Button />} /> [err]: Replace icon component with literal: %s
1,551
0
petrpan-code/palantir/blueprint/packages/tslint-config/test/rules/blueprint-icon-components
petrpan-code/palantir/blueprint/packages/tslint-config/test/rules/blueprint-icon-components/true/test.tsx.lint
<Button icon="tick" /> ~~~~~~ [err % ("<TickIcon />")] <Button icon={<TickIcon />} /> <InputGroup rightElement={<Button />} /> [err]: Replace icon literal with component: %s
3,125
0
petrpan-code/nextauthjs/next-auth/packages/adapter-azure-tables
petrpan-code/nextauthjs/next-auth/packages/adapter-azure-tables/tests/index.test.ts
import { runBasicTests } from "@auth/adapter-test" import { AzureNamedKeyCredential, TableServiceClient, TableClient, } from "@azure/data-tables" import { keys, TableStorageAdapter, withoutKeys } from "../src" import type { AdapterUser, VerificationToken } from "@auth/core/adapters" globalThis.crypto ??= require("node:crypto").webcrypto const testAccount = { // default constants used by a dev instance of azurite name: "devstoreaccount1", key: "Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==", tableEndpoint: "http://127.0.0.1:10002/devstoreaccount1", } const authTableName = "authTest" const credential = new AzureNamedKeyCredential( testAccount.name, testAccount.key ) const authClient = new TableClient( testAccount.tableEndpoint, authTableName, credential, { allowInsecureConnection: true } ) runBasicTests({ adapter: TableStorageAdapter(authClient), db: { async connect() { const serviceClient = new TableServiceClient( testAccount.tableEndpoint, credential, { allowInsecureConnection: true } ) await serviceClient.createTable(authTableName) }, async user(id) { try { const userById = await authClient.getEntity<AdapterUser>(keys.user, id) return withoutKeys(userById) } catch (e) { console.error(e) return null } }, async account(provider_providerAccountId) { try { const account = await authClient.getEntity( keys.account, `${provider_providerAccountId.providerAccountId}_${provider_providerAccountId.provider}` ) return withoutKeys(account) } catch { return null } }, async session(sessionToken) { try { const session = await authClient.getEntity(keys.session, sessionToken) return withoutKeys(session) } catch { return null } }, async verificationToken(identifier_token) { try { const verificationToken = await authClient.getEntity<VerificationToken>( keys.verificationToken, identifier_token.token ) if (verificationToken.identifier !== identifier_token.identifier) { return null } return withoutKeys(verificationToken) } catch { return null } }, }, })
3,132
0
petrpan-code/nextauthjs/next-auth/packages/adapter-d1
petrpan-code/nextauthjs/next-auth/packages/adapter-d1/tests/index.test.ts
import { D1Adapter, up, getRecord, GET_USER_BY_ID_SQL, GET_SESSION_BY_TOKEN_SQL, GET_ACCOUNT_BY_PROVIDER_AND_PROVIDER_ACCOUNT_ID_SQL, GET_VERIFICATION_TOKEN_BY_IDENTIFIER_AND_TOKEN_SQL, } from "../src" import { AdapterSession, AdapterUser, AdapterAccount, } from "@auth/core/adapters" import { D1Database, D1DatabaseAPI } from "@miniflare/d1" import { runBasicTests } from "@auth/adapter-test" import Database from "better-sqlite3" globalThis.crypto ??= require("node:crypto").webcrypto if (process.env.CI) { // TODO: Fix this test('Skipping D1Adapter tests in CI because of "Error: Must use import to load ES Module: next-auth/node_modules/.pnpm/[email protected]/node_modules/undici/lib/llhttp/llhttp.wasm" errors. Should revisit', () => { expect(true).toBe(true) }) process.exit(0) } const sqliteDB = new Database(":memory:") let db = new D1Database(new D1DatabaseAPI(sqliteDB as any)) let adapter = D1Adapter(db) // put stuff here if we need some async init beforeAll(async () => await up(db)) runBasicTests({ adapter, db: { user: async (id) => await getRecord<AdapterUser>(db, GET_USER_BY_ID_SQL, [id]), session: async (sessionToken) => await getRecord<AdapterSession>(db, GET_SESSION_BY_TOKEN_SQL, [ sessionToken, ]), account: async ({ provider, providerAccountId }) => await getRecord<AdapterAccount>( db, GET_ACCOUNT_BY_PROVIDER_AND_PROVIDER_ACCOUNT_ID_SQL, [provider, providerAccountId] ), verificationToken: async ({ identifier, token }) => await getRecord(db, GET_VERIFICATION_TOKEN_BY_IDENTIFIER_AND_TOKEN_SQL, [ identifier, token, ]), }, })
3,141
0
petrpan-code/nextauthjs/next-auth/packages/adapter-dgraph
petrpan-code/nextauthjs/next-auth/packages/adapter-dgraph/tests/index.test.ts
import { DgraphAdapter, format } from "../src" import { client as dgraphClient } from "../src/lib/client" import * as fragments from "../src/lib/graphql/fragments" import { runBasicTests } from "@auth/adapter-test" import fs from "fs" import path from "path" import type { DgraphClientParams } from "../src" const params: DgraphClientParams = { endpoint: "http://localhost:8080/graphql", authToken: "test", jwtAlgorithm: "RS256", jwtSecret: fs.readFileSync(path.join(process.cwd(), "/tests/private.key"), { encoding: "utf8", }), } /** TODO: Add test to `dgraphClient` */ const c = dgraphClient(params) runBasicTests({ adapter: DgraphAdapter(params), db: { id: () => "0x0a0a00a00", async disconnect() { await c.run(/* GraphQL */ ` mutation { deleteUser(filter: {}) { numUids } deleteVerificationToken(filter: {}) { numUids } deleteSession(filter: {}) { numUids } deleteAccount(filter: {}) { numUids } } `) }, async user(id) { const result = await c.run<any>( /* GraphQL */ ` query ($id: ID!) { getUser(id: $id) { ...UserFragment } } ${fragments.User} `, { id } ) return format.from(result) }, async session(sessionToken) { const result = await c.run<any>( /* GraphQL */ ` query ($sessionToken: String!) { querySession(filter: { sessionToken: { eq: $sessionToken } }) { ...SessionFragment user { id } } } ${fragments.Session} `, { sessionToken } ) const { user, ...session } = result?.[0] ?? {} if (!user?.id) return null return format.from({ ...session, userId: user.id }) }, async account(provider_providerAccountId) { const result = await c.run<any>( /* GraphQL */ ` query ($providerAccountId: String = "", $provider: String = "") { queryAccount( filter: { providerAccountId: { eq: $providerAccountId } provider: { eq: $provider } } ) { ...AccountFragment user { id } } } ${fragments.Account} `, provider_providerAccountId ) const account = format.from<any>(result?.[0]) if (!account?.user) return null account.userId = account.user.id delete account.user return account }, async verificationToken(identifier_token) { const result = await c.run<any>( /* GraphQL */ ` query ($identifier: String = "", $token: String = "") { queryVerificationToken( filter: { identifier: { eq: $identifier }, token: { eq: $token } } ) { ...VerificationTokenFragment } } ${fragments.VerificationToken} `, identifier_token ) return format.from(result?.[0]) }, }, })
3,153
0
petrpan-code/nextauthjs/next-auth/packages/adapter-drizzle/tests
petrpan-code/nextauthjs/next-auth/packages/adapter-drizzle/tests/mysql-multi-project-schema/index.test.ts
import { runBasicTests } from "../../../adapter-test" import { DrizzleAdapter } from "../../src" import { db, sessions, verificationTokens, accounts, users } from "./schema" import { eq, and } from "drizzle-orm" import { fixtures } from "../fixtures" globalThis.crypto ??= require("node:crypto").webcrypto runBasicTests({ adapter: DrizzleAdapter(db), fixtures, db: { connect: async () => { await Promise.all([ db.delete(sessions), db.delete(accounts), db.delete(verificationTokens), db.delete(users), ]) }, disconnect: async () => { await Promise.all([ db.delete(sessions), db.delete(accounts), db.delete(verificationTokens), db.delete(users), ]) }, user: async (id) => { const user = await db .select() .from(users) .where(eq(users.id, id)) .then((res) => res[0] ?? null) return user }, session: async (sessionToken) => { const session = await db .select() .from(sessions) .where(eq(sessions.sessionToken, sessionToken)) .then((res) => res[0] ?? null) return session }, account: (provider_providerAccountId) => { const account = db .select() .from(accounts) .where( eq( accounts.providerAccountId, provider_providerAccountId.providerAccountId ) ) .then((res) => res[0] ?? null) return account }, verificationToken: (identifier_token) => db .select() .from(verificationTokens) .where( and( eq(verificationTokens.token, identifier_token.token), eq(verificationTokens.identifier, identifier_token.identifier) ) ) .then((res) => res[0]) ?? null, }, })
3,157
0
petrpan-code/nextauthjs/next-auth/packages/adapter-drizzle/tests
petrpan-code/nextauthjs/next-auth/packages/adapter-drizzle/tests/mysql/index.test.ts
import { runBasicTests } from "../../../adapter-test" import { DrizzleAdapter } from "../../src" import { db, sessions, verificationTokens, accounts, users } from "./schema" import { eq, and } from "drizzle-orm" import { fixtures } from "../fixtures" globalThis.crypto ??= require("node:crypto").webcrypto runBasicTests({ adapter: DrizzleAdapter(db), fixtures, db: { connect: async () => { await Promise.all([ db.delete(sessions), db.delete(accounts), db.delete(verificationTokens), db.delete(users), ]) }, disconnect: async () => { await Promise.all([ db.delete(sessions), db.delete(accounts), db.delete(verificationTokens), db.delete(users), ]) }, user: async (id) => { const user = await db .select() .from(users) .where(eq(users.id, id)) .then((res) => res[0] ?? null) return user }, session: async (sessionToken) => { const session = await db .select() .from(sessions) .where(eq(sessions.sessionToken, sessionToken)) .then((res) => res[0] ?? null) return session }, account: (provider_providerAccountId) => { const account = db .select() .from(accounts) .where( eq( accounts.providerAccountId, provider_providerAccountId.providerAccountId ) ) .then((res) => res[0] ?? null) return account }, verificationToken: (identifier_token) => db .select() .from(verificationTokens) .where( and( eq(verificationTokens.token, identifier_token.token), eq(verificationTokens.identifier, identifier_token.identifier) ) ) .then((res) => res[0]) ?? null, }, })
3,161
0
petrpan-code/nextauthjs/next-auth/packages/adapter-drizzle/tests
petrpan-code/nextauthjs/next-auth/packages/adapter-drizzle/tests/pg-multi-project-schema/index.test.ts
import { runBasicTests } from "../../../adapter-test" import { DrizzleAdapter } from "../../src" import { db, accounts, sessions, users, verificationTokens } from "./schema" import { eq, and } from "drizzle-orm" import { fixtures } from "../fixtures" globalThis.crypto ??= require("node:crypto").webcrypto runBasicTests({ adapter: DrizzleAdapter(db), fixtures, db: { connect: async () => { await Promise.all([ db.delete(sessions), db.delete(accounts), db.delete(verificationTokens), db.delete(users), ]) }, disconnect: async () => { await Promise.all([ db.delete(sessions), db.delete(accounts), db.delete(verificationTokens), db.delete(users), ]) }, user: async (id) => db .select() .from(users) .where(eq(users.id, id)) .then((res) => res[0] ?? null), session: (sessionToken) => db .select() .from(sessions) .where(eq(sessions.sessionToken, sessionToken)) .then((res) => res[0] ?? null), account: (provider_providerAccountId) => { return db .select() .from(accounts) .where( eq( accounts.providerAccountId, provider_providerAccountId.providerAccountId ) ) .then((res) => res[0] ?? null) }, verificationToken: (identifier_token) => db .select() .from(verificationTokens) .where( and( eq(verificationTokens.token, identifier_token.token), eq(verificationTokens.identifier, identifier_token.identifier) ) ) .then((res) => res[0] ?? null), }, })
3,166
0
petrpan-code/nextauthjs/next-auth/packages/adapter-drizzle/tests
petrpan-code/nextauthjs/next-auth/packages/adapter-drizzle/tests/pg/index.test.ts
import { runBasicTests } from "../../../adapter-test" import { DrizzleAdapter } from "../../src" import { db, accounts, sessions, users, verificationTokens } from "./schema" import { eq, and } from "drizzle-orm" import { fixtures } from "../fixtures" globalThis.crypto ??= require("node:crypto").webcrypto runBasicTests({ adapter: DrizzleAdapter(db), fixtures, db: { connect: async () => { await Promise.all([ db.delete(sessions), db.delete(accounts), db.delete(verificationTokens), db.delete(users), ]) }, disconnect: async () => { await Promise.all([ db.delete(sessions), db.delete(accounts), db.delete(verificationTokens), db.delete(users), ]) }, user: async (id) => db .select() .from(users) .where(eq(users.id, id)) .then((res) => res[0] ?? null), session: (sessionToken) => db .select() .from(sessions) .where(eq(sessions.sessionToken, sessionToken)) .then((res) => res[0] ?? null), account: (provider_providerAccountId) => { return db .select() .from(accounts) .where( eq( accounts.providerAccountId, provider_providerAccountId.providerAccountId ) ) .then((res) => res[0] ?? null) }, verificationToken: (identifier_token) => db .select() .from(verificationTokens) .where( and( eq(verificationTokens.token, identifier_token.token), eq(verificationTokens.identifier, identifier_token.identifier) ) ) .then((res) => res[0] ?? null), }, })
3,171
0
petrpan-code/nextauthjs/next-auth/packages/adapter-drizzle/tests
petrpan-code/nextauthjs/next-auth/packages/adapter-drizzle/tests/sqlite-multi-project-schema/index.test.ts
import { runBasicTests } from "../../../adapter-test" import { DrizzleAdapter } from "../../src" import { db, accounts, sessions, users, verificationTokens } from "./schema" import { eq, and } from "drizzle-orm" globalThis.crypto ??= require("node:crypto").webcrypto runBasicTests({ adapter: DrizzleAdapter(db), db: { connect: async () => { await Promise.all([ db.delete(sessions), db.delete(accounts), db.delete(verificationTokens), db.delete(users), ]) }, disconnect: async () => { await Promise.all([ db.delete(sessions), db.delete(accounts), db.delete(verificationTokens), db.delete(users), ]) }, user: (id) => db.select().from(users).where(eq(users.id, id)).get() ?? null, session: (sessionToken) => db .select() .from(sessions) .where(eq(sessions.sessionToken, sessionToken)) .get() ?? null, account: (provider_providerAccountId) => { return ( db .select() .from(accounts) .where( eq( accounts.providerAccountId, provider_providerAccountId.providerAccountId ) ) .get() ?? null ) }, verificationToken: (identifier_token) => db .select() .from(verificationTokens) .where( and( eq(verificationTokens.token, identifier_token.token), eq(verificationTokens.identifier, identifier_token.identifier) ) ) .get() ?? null, }, })
3,175
0
petrpan-code/nextauthjs/next-auth/packages/adapter-drizzle/tests
petrpan-code/nextauthjs/next-auth/packages/adapter-drizzle/tests/sqlite/index.test.ts
import { runBasicTests } from "../../../adapter-test" import { DrizzleAdapter } from "../../src" import { db, accounts, sessions, users, verificationTokens } from "./schema" import { eq, and } from "drizzle-orm" globalThis.crypto ??= require("node:crypto").webcrypto runBasicTests({ adapter: DrizzleAdapter(db), db: { connect: async () => { await Promise.all([ db.delete(sessions), db.delete(accounts), db.delete(verificationTokens), db.delete(users), ]) }, disconnect: async () => { await Promise.all([ db.delete(sessions), db.delete(accounts), db.delete(verificationTokens), db.delete(users), ]) }, user: (id) => db.select().from(users).where(eq(users.id, id)).get() ?? null, session: (sessionToken) => db .select() .from(sessions) .where(eq(sessions.sessionToken, sessionToken)) .get() ?? null, account: (provider_providerAccountId) => { return ( db .select() .from(accounts) .where( eq( accounts.providerAccountId, provider_providerAccountId.providerAccountId ) ) .get() ?? null ) }, verificationToken: (identifier_token) => db .select() .from(verificationTokens) .where( and( eq(verificationTokens.token, identifier_token.token), eq(verificationTokens.identifier, identifier_token.identifier) ) ) .get() ?? null, }, })
3,184
0
petrpan-code/nextauthjs/next-auth/packages/adapter-dynamodb
petrpan-code/nextauthjs/next-auth/packages/adapter-dynamodb/tests/format.test.ts
import { format } from "../src/" describe("dynamodb utils.format", () => { it("format.to() preserves non-Date non-expires properties", () => { expect( format.to({ pk: "test-pk", email: "[email protected]", }) ).toEqual({ pk: "test-pk", email: "[email protected]", }) }) it("format.to() converts non-expires Date properties to ISO strings", () => { const date = new Date() expect( format.to({ dateProp: date, }) ).toEqual({ dateProp: date.toISOString(), }) }) it("format.to() converts expires property to a UNIX timestamp", () => { // DynamoDB requires that the property used for TTL is a UNIX timestamp. const date = new Date() const timestamp = date.getTime() / 1000 expect( format.to({ expires: date, }) ).toEqual({ expires: timestamp, }) }) it("format.from() preserves non-special attributes", () => { expect( format.from({ testAttr1: "test-value", testAttr2: 5, }) ).toEqual({ testAttr1: "test-value", testAttr2: 5, }) }) it("format.from() removes dynamodb key attributes", () => { expect( format.from({ pk: "test-pk", sk: "test-sk", GSI1PK: "test-GSI1PK", GSI1SK: "test-GSI1SK", }) ).toEqual({}) }) it("format.from() only removes type attribute from Session, VT, and User", () => { expect(format.from({ type: "SESSION" })).toEqual({}) expect(format.from({ type: "VT" })).toEqual({}) expect(format.from({ type: "USER" })).toEqual({}) expect(format.from({ type: "ANYTHING" })).toEqual({ type: "ANYTHING" }) expect(format.from({ type: "ELSE" })).toEqual({ type: "ELSE" }) }) it("format.from() converts ISO strings to Date instances", () => { const date = new Date() expect( format.from({ someDate: date.toISOString(), }) ).toEqual({ someDate: date, }) }) it("format.from() converts expires attribute from timestamp to Date instance", () => { // AdapterSession["expires"] and VerificationToken["expires"] are both meant // to be Date instances. const date = new Date() const timestamp = date.getTime() / 1000 expect( format.from({ expires: timestamp, }) ).toEqual({ expires: date, }) }) it("format.from() converts expires attribute from ISO string to Date instance", () => { // Due to a bug in an old version, some expires attributes were stored as // ISO strings, so we need to handle those properly too. const date = new Date() expect( format.from({ expires: date.toISOString(), }) ).toEqual({ expires: date, }) }) it("format.from(format.to()) preserves expires attribute", () => { const date = new Date() expect( format.from( format.to({ expires: date, }) ) ).toEqual({ expires: date, }) }) })
3,185
0
petrpan-code/nextauthjs/next-auth/packages/adapter-dynamodb
petrpan-code/nextauthjs/next-auth/packages/adapter-dynamodb/tests/index.test.ts
import { DynamoDB } from "@aws-sdk/client-dynamodb" import { DynamoDBDocument } from "@aws-sdk/lib-dynamodb" import { DynamoDBAdapter } from "../src" import { runBasicTests } from "@auth/adapter-test" import { format } from "../src/" const config = { endpoint: "http://127.0.0.1:8000", region: "eu-central-1", tls: false, credentials: { accessKeyId: "foo", secretAccessKey: "bar", }, } const client = DynamoDBDocument.from(new DynamoDB(config), { marshallOptions: { convertEmptyValues: true, removeUndefinedValues: true, convertClassInstanceToMap: true, }, }) const adapter = DynamoDBAdapter(client) const TableName = "next-auth" runBasicTests({ adapter, db: { async user(id) { const user = await client.get({ TableName, Key: { pk: `USER#${id}`, sk: `USER#${id}`, }, }) return format.from(user.Item) }, async session(token) { const session = await client.query({ TableName, IndexName: "GSI1", KeyConditionExpression: "#gsi1pk = :gsi1pk AND #gsi1sk = :gsi1sk", ExpressionAttributeNames: { "#gsi1pk": "GSI1PK", "#gsi1sk": "GSI1SK", }, ExpressionAttributeValues: { ":gsi1pk": `SESSION#${token}`, ":gsi1sk": `SESSION#${token}`, }, }) return format.from(session.Items?.[0]) }, async account({ provider, providerAccountId }) { const account = await client.query({ TableName, IndexName: "GSI1", KeyConditionExpression: "#gsi1pk = :gsi1pk AND #gsi1sk = :gsi1sk", ExpressionAttributeNames: { "#gsi1pk": "GSI1PK", "#gsi1sk": "GSI1SK", }, ExpressionAttributeValues: { ":gsi1pk": `ACCOUNT#${provider}`, ":gsi1sk": `ACCOUNT#${providerAccountId}`, }, }) return format.from(account.Items?.[0]) }, async verificationToken({ token, identifier }) { const vt = await client.get({ TableName, Key: { pk: `VT#${identifier}`, sk: `VT#${token}`, }, }) return format.from(vt.Item) }, }, })
3,191
0
petrpan-code/nextauthjs/next-auth/packages/adapter-edgedb
petrpan-code/nextauthjs/next-auth/packages/adapter-edgedb/tests/index.test.ts
import { runBasicTests } from "@auth/adapter-test" import { EdgeDBAdapter } from "../src" import { createClient } from "edgedb" if (process.env.CI) { // TODO: Fix this test('Skipping EdgeDBAdapter tests in CI because of "Request failed" errors. Should revisit', () => { expect(true).toBe(true) }) process.exit(0) } const client = createClient(); runBasicTests({ adapter: EdgeDBAdapter(client), db: { connect: async () => { await client.query(` delete User; delete Account; delete Session; delete VerificationToken; `) }, disconnect: async () => { await client.query(` delete User; delete Account; delete Session; delete VerificationToken; `) }, user: async (id) => { return await client.querySingle(` select User { id, email, emailVerified, name, image } filter .id = <uuid>$id `, { id }) }, account: async ({ providerAccountId, provider }) => { return await client.querySingle(` select Account { provider, providerAccountId, type, access_token, expires_at, id_token, refresh_token, token_type, scope, session_state, id, userId } filter .providerAccountId = <str>$providerAccountId and .provider = <str>$provider `, { providerAccountId, provider }) }, session: async (sessionToken) => { return await client.querySingle(` select Session { userId, id, expires, sessionToken, } filter .sessionToken = <str>$sessionToken `, { sessionToken }) }, async verificationToken({ token, identifier }) { return await client.querySingle(` select VerificationToken { identifier, expires, token, } filter .token = <str>$token and .identifier = <str>$identifier `, { token, identifier }) }, }, })
3,218
0
petrpan-code/nextauthjs/next-auth/packages/adapter-fauna
petrpan-code/nextauthjs/next-auth/packages/adapter-fauna/tests/index.test.ts
import { collections, FaunaAdapter, format, indexes, query } from "../src" import { runBasicTests } from "@auth/adapter-test" import { Client as FaunaClient, Get, Match, Ref } from "faunadb" const client = new FaunaClient({ secret: "secret", scheme: "http", domain: "localhost", port: 8443, }) const q = query(client, format.from) runBasicTests({ adapter: FaunaAdapter(client), db: { disconnect: async () => await client.close({ force: true }), user: async (id) => await q(Get(Ref(collections.Users, id))), session: async (sessionToken) => await q(Get(Match(indexes.SessionByToken, sessionToken))), async account({ provider, providerAccountId }) { const key = [provider, providerAccountId] const ref = Match(indexes.AccountByProviderAndProviderAccountId, key) return await q(Get(ref)) }, async verificationToken({ identifier, token }) { const key = [identifier, token] const ref = Match(indexes.VerificationTokenByIdentifierAndToken, key) const verificationToken = await q(Get(ref)) // @ts-expect-error if (verificationToken) delete verificationToken.id return verificationToken }, }, })
3,226
0
petrpan-code/nextauthjs/next-auth/packages/adapter-firebase
petrpan-code/nextauthjs/next-auth/packages/adapter-firebase/tests/index.test.ts
import { runBasicTests } from "@auth/adapter-test" import { FirestoreAdapter, type FirebaseAdapterConfig } from "../src" import { collectionsFactory, initFirestore, getDoc, getOneDoc, mapFieldsFactory, } from "../src" describe.each([ { namingStrategy: "snake_case" }, { namingStrategy: "default" }, ] as Partial<FirebaseAdapterConfig>[])( "FirebaseAdapter with config: %s", (config) => { config.name = `next-auth-test-${config.namingStrategy}` config.projectId = "next-auth-test" config.databaseURL = "http://localhost:8080" const db = initFirestore(config) const preferSnakeCase = config.namingStrategy === "snake_case" const mapper = mapFieldsFactory(preferSnakeCase) const C = collectionsFactory(db, preferSnakeCase) for (const [name, collection] of Object.entries(C)) { test(`collection "${name}" should be empty`, async () => { expect((await collection.count().get()).data().count).toBe(0) }) } runBasicTests({ adapter: FirestoreAdapter(config), db: { disconnect: async () => await db.terminate(), session: (sessionToken) => getOneDoc( C.sessions.where(mapper.toDb("sessionToken"), "==", sessionToken) ), user: (userId) => getDoc(C.users.doc(userId)), account: ({ provider, providerAccountId }) => getOneDoc( C.accounts .where("provider", "==", provider) .where(mapper.toDb("providerAccountId"), "==", providerAccountId) ), verificationToken: ({ identifier, token }) => getOneDoc( C.verification_tokens .where("identifier", "==", identifier) .where("token", "==", token) ), }, }) } )
3,262
0
petrpan-code/nextauthjs/next-auth/packages/adapter-hasura
petrpan-code/nextauthjs/next-auth/packages/adapter-hasura/tests/index.test.ts
import { runBasicTests } from "@auth/adapter-test" import { HasuraAdapter, format } from "../src" import { useFragment } from "../src/lib/generated" import { AccountFragmentDoc, DeleteAllDocument, GetAccountDocument, GetSessionDocument, GetUserDocument, GetVerificationTokenDocument, SessionFragmentDoc, UserFragmentDoc, VerificationTokenFragmentDoc, } from "../src/lib/generated/graphql" import { client as hasuraClient } from "../src/lib/client" const client = hasuraClient({ endpoint: "http://localhost:8080/v1/graphql", adminSecret: "myadminsecretkey", }) runBasicTests({ adapter: HasuraAdapter({ adminSecret: "myadminsecretkey", endpoint: "http://localhost:8080/v1/graphql", }), db: { async connect() { await client.run(DeleteAllDocument) }, async disconnect() { await client.run(DeleteAllDocument) }, async user(id) { const { users_by_pk } = await client.run(GetUserDocument, { id }) const user = useFragment(UserFragmentDoc, users_by_pk) return format.from(user) }, async account(params) { const { accounts } = await client.run(GetAccountDocument, params) return useFragment(AccountFragmentDoc, accounts?.[0]) ?? null }, async session(sessionToken) { const { sessions_by_pk } = await client.run(GetSessionDocument, { sessionToken, }) return format.from(useFragment(SessionFragmentDoc, sessions_by_pk)) }, async verificationToken(params) { const { verification_tokens } = await client.run( GetVerificationTokenDocument, params ) const verificationToken = verification_tokens?.[0] return format.from( useFragment(VerificationTokenFragmentDoc, verificationToken) ) }, }, })
3,268
0
petrpan-code/nextauthjs/next-auth/packages/adapter-kysely
petrpan-code/nextauthjs/next-auth/packages/adapter-kysely/tests/index.test.ts
import { runBasicTests } from "@auth/adapter-test" import { Pool } from "pg" import { Kysely, MysqlDialect, PostgresDialect, SchemaModule, sql, SqliteAdapter, SqliteDialect, } from "kysely" import { KyselyAdapter, KyselyAuth } from "../src" import { createPool } from "mysql2" import SqliteDatabase from "better-sqlite3" import type { Database } from "../src" import { DataTypeExpression } from "kysely/dist/cjs/parser/data-type-parser" type BuiltInDialect = "postgres" | "mysql" | "sqlite" const POOL_SIZE = 20 const DIALECT_CONFIGS = { postgres: { host: "localhost", database: "kysely_test", user: "kysely", port: 5434, max: POOL_SIZE, }, mysql: { database: "kysely_test", host: "localhost", user: "kysely", password: "kysely", port: 3308, supportBigNumbers: true, bigNumberStrings: true, connectionLimit: POOL_SIZE, }, sqlite: { databasePath: ":memory:", }, } as const async function dropDatabase(db: Kysely<Database>): Promise<void> { await Promise.all([ db.schema.dropTable("Account").ifExists().execute(), db.schema.dropTable("Session").ifExists().execute(), db.schema.dropTable("User").ifExists().execute(), db.schema.dropTable("VerificationToken").ifExists().execute(), ]) } export function createTableWithId( schema: SchemaModule, dialect: BuiltInDialect, tableName: string ) { const builder = schema.createTable(tableName) if (dialect === "postgres") { return builder.addColumn("id", "uuid", (col) => col.primaryKey().defaultTo(sql`gen_random_uuid()`) ) } else if (dialect === "mysql") { return builder.addColumn("id", "varchar(36)", (col) => col.primaryKey().defaultTo(sql`(UUID())`) ) } else { return builder.addColumn("id", "integer", (col) => col.autoIncrement().primaryKey() ) } } async function createDatabase( db: Kysely<Database>, dialect: BuiltInDialect ): Promise<void> { const defaultTimestamp = { postgres: sql`NOW()`, mysql: sql`NOW(3)`, sqlite: sql`CURRENT_TIMESTAMP`, }[dialect] const uuidColumnType: DataTypeExpression = dialect === "mysql" ? "varchar(36)" : "uuid" const dateColumnType: DataTypeExpression = dialect === "mysql" ? sql`DATETIME(3)` : "timestamptz" const textColumnType: DataTypeExpression = dialect === "mysql" ? "varchar(255)" : "text" await dropDatabase(db) await createTableWithId(db.schema, dialect, "User") .addColumn("name", textColumnType) .addColumn("email", textColumnType, (col) => col.unique().notNull()) .addColumn("emailVerified", dateColumnType, (col) => col.defaultTo(defaultTimestamp) ) .addColumn("image", textColumnType) .execute() let createAccountTable = createTableWithId(db.schema, dialect, "Account") .addColumn("userId", uuidColumnType, (col) => col.references("User.id").onDelete("cascade").notNull() ) .addColumn("type", textColumnType, (col) => col.notNull()) .addColumn("provider", textColumnType, (col) => col.notNull()) .addColumn("providerAccountId", textColumnType, (col) => col.notNull()) .addColumn("refresh_token", textColumnType) .addColumn("access_token", textColumnType) .addColumn("expires_at", "bigint") .addColumn("token_type", textColumnType) .addColumn("scope", textColumnType) .addColumn("id_token", textColumnType) .addColumn("session_state", textColumnType) if (dialect === "mysql") createAccountTable = createAccountTable.addForeignKeyConstraint( "Account_userId_fk", ["userId"], "User", ["id"], (cb) => cb.onDelete("cascade") ) await createAccountTable.execute() let createSessionTable = createTableWithId(db.schema, dialect, "Session") .addColumn("userId", uuidColumnType, (col) => col.references("User.id").onDelete("cascade").notNull() ) .addColumn("sessionToken", textColumnType, (col) => col.notNull().unique()) .addColumn("expires", dateColumnType, (col) => col.notNull()) if (dialect === "mysql") createSessionTable = createSessionTable.addForeignKeyConstraint( "Session_userId_fk", ["userId"], "User", ["id"], (cb) => cb.onDelete("cascade") ) await createSessionTable.execute() await db.schema .createTable("VerificationToken") .addColumn("identifier", textColumnType, (col) => col.notNull()) .addColumn("token", textColumnType, (col) => col.notNull().unique()) .addColumn("expires", dateColumnType, (col) => col.notNull()) .execute() await db.schema .createIndex("Account_userId_index") .on("Account") .column("userId") .execute() } const runDialectBasicTests = ( db: Kysely<Database>, dialect: BuiltInDialect ) => { const datesStoredAsISOStrings = db.getExecutor().adapter instanceof SqliteAdapter runBasicTests({ adapter: KyselyAdapter(db), db: { async connect() { await dropDatabase(db) await createDatabase(db, dialect) }, async disconnect() { await db.destroy() }, async user(userId) { const user = (await db .selectFrom("User") .selectAll() .where("id", "=", userId) .executeTakeFirst()) ?? null if (datesStoredAsISOStrings && user?.emailVerified) user.emailVerified = new Date(user.emailVerified) return user }, async account({ provider, providerAccountId }) { const result = await db .selectFrom("Account") .selectAll() .where("provider", "=", provider) .where("providerAccountId", "=", providerAccountId) .executeTakeFirst() if (!result) return null const { ...account } = result if (typeof account.expires_at === "string") account.expires_at = Number(account.expires_at) return account }, async session(sessionToken) { const session = (await db .selectFrom("Session") .selectAll() .where("sessionToken", "=", sessionToken) .executeTakeFirst()) ?? null if (datesStoredAsISOStrings && session?.expires) session.expires = new Date(session.expires) return session }, async verificationToken({ identifier, token }) { const verificationToken = await db .selectFrom("VerificationToken") .selectAll() .where("identifier", "=", identifier) .where("token", "=", token) .executeTakeFirstOrThrow() if (datesStoredAsISOStrings) verificationToken.expires = new Date(verificationToken.expires) return verificationToken }, }, }) } describe("Testing PostgresDialect", () => { const db = new KyselyAuth<Database>({ dialect: new PostgresDialect({ pool: new Pool(DIALECT_CONFIGS.postgres), }), }) runDialectBasicTests(db, "postgres") }) describe("Testing MysqlDialect", () => { const db = new KyselyAuth<Database>({ dialect: new MysqlDialect({ pool: createPool(DIALECT_CONFIGS.mysql), }), }) runDialectBasicTests(db, "mysql") }) describe("Testing SqliteDialect", () => { const db = new KyselyAuth<Database>({ dialect: new SqliteDialect({ database: async () => new SqliteDatabase(DIALECT_CONFIGS.sqlite.databasePath), }), }) runDialectBasicTests(db, "sqlite") })
3,276
0
petrpan-code/nextauthjs/next-auth/packages/adapter-mikro-orm
petrpan-code/nextauthjs/next-auth/packages/adapter-mikro-orm/tests/entities.test.ts
import type { SqliteDriver } from "@mikro-orm/sqlite" import { MikroOrmAdapter, defaultEntities } from "../src" import { Cascade, Collection, Entity, OneToMany, PrimaryKey, Property, Unique, MikroORM, wrap, Options, types, } from "@mikro-orm/core" import { runBasicTests } from "@auth/adapter-test" globalThis.crypto ??= require("node:crypto").webcrypto @Entity() export class User implements defaultEntities.User { @PrimaryKey() @Property({ type: types.string }) id: string = crypto.randomUUID() @Property({ type: types.string, nullable: true }) name?: string @Property({ type: types.string, nullable: true }) @Unique() email: string = "" @Property({ type: "Date", nullable: true }) emailVerified: Date | null = null @Property({ type: types.string, nullable: true }) image?: string @OneToMany({ entity: "Session", mappedBy: (session: defaultEntities.Session) => session.user, hidden: true, orphanRemoval: true, cascade: [Cascade.ALL], }) sessions = new Collection<defaultEntities.Session>(this) @OneToMany({ entity: "Account", mappedBy: (account: defaultEntities.Account) => account.user, hidden: true, orphanRemoval: true, cascade: [Cascade.ALL], }) accounts = new Collection<defaultEntities.Account>(this) @Property({ type: types.string, hidden: true }) role = "ADMIN" } @Entity() export class VeryImportantEntity { @PrimaryKey() @Property({ type: types.string }) id: string = crypto.randomUUID() @Property({ type: types.boolean }) important = true } let _init: MikroORM const entities = [ User, defaultEntities.Account, defaultEntities.Session, defaultEntities.VerificationToken, VeryImportantEntity, ] const config: Options<SqliteDriver> = { dbName: "./db.sqlite", type: "sqlite", entities, debug: process.env.DEBUG === "true" || process.env.DEBUG?.includes("db"), } async function getORM() { if (_init) return _init _init = await MikroORM.init(config) return _init } runBasicTests({ adapter: MikroOrmAdapter(config, { entities: { User } }), db: { async connect() { const orm = await getORM() await orm.getSchemaGenerator().dropSchema() await orm.getSchemaGenerator().createSchema() }, async disconnect() { const orm = await getORM() // its fine to tear down the connection if it has been already closed await orm .getSchemaGenerator() .dropSchema() .catch(() => null) await orm.close().catch(() => null) }, async verificationToken(identifier_token) { const orm = await getORM() const token = await orm.em .fork() .findOne(defaultEntities.VerificationToken, identifier_token) if (!token) return null return wrap(token).toObject() }, async user(id) { const orm = await getORM() const user = await orm.em.fork().findOne(defaultEntities.User, { id }) if (!user) return null return wrap(user).toObject() }, async account(provider_providerAccountId) { const orm = await getORM() const account = await orm.em .fork() .findOne(defaultEntities.Account, { ...provider_providerAccountId }) if (!account) return null return wrap(account).toObject() }, async session(sessionToken) { const orm = await getORM() const session = await orm.em .fork() .findOne(defaultEntities.Session, { sessionToken }) if (!session) return null return wrap(session).toObject() }, }, })
3,277
0
petrpan-code/nextauthjs/next-auth/packages/adapter-mikro-orm
petrpan-code/nextauthjs/next-auth/packages/adapter-mikro-orm/tests/schema.test.ts
import { MikroORM, Options } from "@mikro-orm/core" import { SqliteDriver } from "@mikro-orm/sqlite" import { defaultEntities } from "../src" const config: Options<SqliteDriver> = { dbName: "./db.sqlite", type: "sqlite", entities: [ defaultEntities.User, defaultEntities.Account, defaultEntities.Session, defaultEntities.VerificationToken, ], } it("run migrations", async () => { const orm = await MikroORM.init(config) await orm.getSchemaGenerator().dropSchema() const createSchemaSQL = await orm.getSchemaGenerator().getCreateSchemaSQL() expect(createSchemaSQL).toMatchSnapshot("createSchemaSQL") const targetSchema = await orm.getSchemaGenerator().getTargetSchema() expect(targetSchema).toMatchSnapshot("targetSchema") await orm.getSchemaGenerator().dropSchema() await orm.close().catch(() => null) })
3,278
0
petrpan-code/nextauthjs/next-auth/packages/adapter-mikro-orm/tests
petrpan-code/nextauthjs/next-auth/packages/adapter-mikro-orm/tests/__snapshots__/schema.test.ts.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`run migrations: createSchemaSQL 1`] = ` "pragma foreign_keys = off; create table \`verification_token\` (\`token\` text not null, \`expires\` datetime not null, \`identifier\` text not null, primary key (\`token\`)); create unique index \`verification_token_token_identifier_unique\` on \`verification_token\` (\`token\`, \`identifier\`); create table \`user\` (\`id\` text not null, \`name\` text null, \`email\` text null, \`email_verified\` datetime null, \`image\` text null, primary key (\`id\`)); create unique index \`user_email_unique\` on \`user\` (\`email\`); create table \`account\` (\`id\` text not null, \`user_id\` text not null, \`type\` text not null, \`provider\` text not null, \`provider_account_id\` text not null, \`refresh_token\` text null, \`access_token\` text null, \`expires_at\` integer null, \`token_type\` text null, \`scope\` text null, \`id_token\` text null, \`session_state\` text null, constraint \`account_user_id_foreign\` foreign key(\`user_id\`) references \`user\`(\`id\`) on delete cascade on update cascade, primary key (\`id\`)); create index \`account_user_id_index\` on \`account\` (\`user_id\`); create unique index \`account_provider_provider_account_id_unique\` on \`account\` (\`provider\`, \`provider_account_id\`); create table \`session\` (\`id\` text not null, \`user_id\` text not null, \`expires\` datetime not null, \`session_token\` text not null, constraint \`session_user_id_foreign\` foreign key(\`user_id\`) references \`user\`(\`id\`) on delete cascade on update cascade, primary key (\`id\`)); create index \`session_user_id_index\` on \`session\` (\`user_id\`); create unique index \`session_session_token_unique\` on \`session\` (\`session_token\`); pragma foreign_keys = on; " `; exports[`run migrations: targetSchema 1`] = ` { "name": undefined, "namespaces": [], "tables": [ { "checks": [], "columns": { "expires": { "autoincrement": false, "comment": undefined, "default": undefined, "enumItems": undefined, "extra": undefined, "length": 0, "mappedType": "datetime", "name": "expires", "nullable": false, "precision": undefined, "primary": false, "scale": undefined, "type": "datetime", "unsigned": false, }, "identifier": { "autoincrement": false, "comment": undefined, "default": undefined, "enumItems": undefined, "extra": undefined, "length": undefined, "mappedType": "text", "name": "identifier", "nullable": false, "precision": undefined, "primary": false, "scale": undefined, "type": "text", "unsigned": false, }, "token": { "autoincrement": false, "comment": undefined, "default": undefined, "enumItems": undefined, "extra": undefined, "length": undefined, "mappedType": "text", "name": "token", "nullable": false, "precision": undefined, "primary": false, "scale": undefined, "type": "text", "unsigned": false, }, }, "comment": undefined, "foreignKeys": {}, "indexes": [ { "columnNames": [ "token", "identifier", ], "composite": true, "expression": undefined, "keyName": "verification_token_token_identifier_unique", "primary": false, "type": undefined, "unique": true, }, { "columnNames": [ "token", ], "composite": false, "expression": undefined, "keyName": "primary", "primary": true, "type": undefined, "unique": true, }, ], "name": "verification_token", "schema": undefined, }, { "checks": [], "columns": { "email": { "autoincrement": false, "comment": undefined, "default": undefined, "enumItems": undefined, "extra": undefined, "length": undefined, "mappedType": "text", "name": "email", "nullable": true, "precision": undefined, "primary": false, "scale": undefined, "type": "text", "unsigned": false, }, "email_verified": { "autoincrement": false, "comment": undefined, "default": undefined, "enumItems": undefined, "extra": undefined, "length": 0, "mappedType": "datetime", "name": "email_verified", "nullable": true, "precision": undefined, "primary": false, "scale": undefined, "type": "datetime", "unsigned": false, }, "id": { "autoincrement": false, "comment": undefined, "default": undefined, "enumItems": undefined, "extra": undefined, "length": undefined, "mappedType": "text", "name": "id", "nullable": false, "precision": undefined, "primary": false, "scale": undefined, "type": "text", "unsigned": false, }, "image": { "autoincrement": false, "comment": undefined, "default": undefined, "enumItems": undefined, "extra": undefined, "length": undefined, "mappedType": "text", "name": "image", "nullable": true, "precision": undefined, "primary": false, "scale": undefined, "type": "text", "unsigned": false, }, "name": { "autoincrement": false, "comment": undefined, "default": undefined, "enumItems": undefined, "extra": undefined, "length": undefined, "mappedType": "text", "name": "name", "nullable": true, "precision": undefined, "primary": false, "scale": undefined, "type": "text", "unsigned": false, }, }, "comment": undefined, "foreignKeys": {}, "indexes": [ { "columnNames": [ "email", ], "composite": false, "keyName": "user_email_unique", "primary": false, "unique": true, }, { "columnNames": [ "id", ], "composite": false, "expression": undefined, "keyName": "primary", "primary": true, "type": undefined, "unique": true, }, ], "name": "user", "schema": undefined, }, { "checks": [], "columns": { "access_token": { "autoincrement": false, "comment": undefined, "default": undefined, "enumItems": undefined, "extra": undefined, "length": undefined, "mappedType": "text", "name": "access_token", "nullable": true, "precision": undefined, "primary": false, "scale": undefined, "type": "text", "unsigned": false, }, "expires_at": { "autoincrement": false, "comment": undefined, "default": undefined, "enumItems": undefined, "extra": undefined, "length": undefined, "mappedType": "integer", "name": "expires_at", "nullable": true, "precision": undefined, "primary": false, "scale": undefined, "type": "integer", "unsigned": false, }, "id": { "autoincrement": false, "comment": undefined, "default": undefined, "enumItems": undefined, "extra": undefined, "length": undefined, "mappedType": "text", "name": "id", "nullable": false, "precision": undefined, "primary": false, "scale": undefined, "type": "text", "unsigned": false, }, "id_token": { "autoincrement": false, "comment": undefined, "default": undefined, "enumItems": undefined, "extra": undefined, "length": undefined, "mappedType": "text", "name": "id_token", "nullable": true, "precision": undefined, "primary": false, "scale": undefined, "type": "text", "unsigned": false, }, "provider": { "autoincrement": false, "comment": undefined, "default": undefined, "enumItems": undefined, "extra": undefined, "length": undefined, "mappedType": "text", "name": "provider", "nullable": false, "precision": undefined, "primary": false, "scale": undefined, "type": "text", "unsigned": false, }, "provider_account_id": { "autoincrement": false, "comment": undefined, "default": undefined, "enumItems": undefined, "extra": undefined, "length": undefined, "mappedType": "text", "name": "provider_account_id", "nullable": false, "precision": undefined, "primary": false, "scale": undefined, "type": "text", "unsigned": false, }, "refresh_token": { "autoincrement": false, "comment": undefined, "default": undefined, "enumItems": undefined, "extra": undefined, "length": undefined, "mappedType": "text", "name": "refresh_token", "nullable": true, "precision": undefined, "primary": false, "scale": undefined, "type": "text", "unsigned": false, }, "scope": { "autoincrement": false, "comment": undefined, "default": undefined, "enumItems": undefined, "extra": undefined, "length": undefined, "mappedType": "text", "name": "scope", "nullable": true, "precision": undefined, "primary": false, "scale": undefined, "type": "text", "unsigned": false, }, "session_state": { "autoincrement": false, "comment": undefined, "default": undefined, "enumItems": undefined, "extra": undefined, "length": undefined, "mappedType": "text", "name": "session_state", "nullable": true, "precision": undefined, "primary": false, "scale": undefined, "type": "text", "unsigned": false, }, "token_type": { "autoincrement": false, "comment": undefined, "default": undefined, "enumItems": undefined, "extra": undefined, "length": undefined, "mappedType": "text", "name": "token_type", "nullable": true, "precision": undefined, "primary": false, "scale": undefined, "type": "text", "unsigned": false, }, "type": { "autoincrement": false, "comment": undefined, "default": undefined, "enumItems": undefined, "extra": undefined, "length": undefined, "mappedType": "text", "name": "type", "nullable": false, "precision": undefined, "primary": false, "scale": undefined, "type": "text", "unsigned": false, }, "user_id": { "autoincrement": false, "comment": undefined, "default": undefined, "enumItems": undefined, "extra": undefined, "length": undefined, "mappedType": "text", "name": "user_id", "nullable": false, "precision": undefined, "primary": false, "scale": undefined, "type": "text", "unsigned": false, }, }, "comment": undefined, "foreignKeys": { "account_user_id_foreign": { "columnNames": [ "user_id", ], "constraintName": "account_user_id_foreign", "deleteRule": "cascade", "localTableName": "account", "referencedColumnNames": [ "id", ], "referencedTableName": "user", "updateRule": "cascade", }, }, "indexes": [ { "columnNames": [ "user_id", ], "composite": false, "keyName": "account_user_id_index", "primary": false, "unique": false, }, { "columnNames": [ "provider", "provider_account_id", ], "composite": true, "expression": undefined, "keyName": "account_provider_provider_account_id_unique", "primary": false, "type": undefined, "unique": true, }, { "columnNames": [ "id", ], "composite": false, "expression": undefined, "keyName": "primary", "primary": true, "type": undefined, "unique": true, }, ], "name": "account", "schema": undefined, }, { "checks": [], "columns": { "expires": { "autoincrement": false, "comment": undefined, "default": undefined, "enumItems": undefined, "extra": undefined, "length": 0, "mappedType": "datetime", "name": "expires", "nullable": false, "precision": undefined, "primary": false, "scale": undefined, "type": "datetime", "unsigned": false, }, "id": { "autoincrement": false, "comment": undefined, "default": undefined, "enumItems": undefined, "extra": undefined, "length": undefined, "mappedType": "text", "name": "id", "nullable": false, "precision": undefined, "primary": false, "scale": undefined, "type": "text", "unsigned": false, }, "session_token": { "autoincrement": false, "comment": undefined, "default": undefined, "enumItems": undefined, "extra": undefined, "length": undefined, "mappedType": "text", "name": "session_token", "nullable": false, "precision": undefined, "primary": false, "scale": undefined, "type": "text", "unsigned": false, }, "user_id": { "autoincrement": false, "comment": undefined, "default": undefined, "enumItems": undefined, "extra": undefined, "length": undefined, "mappedType": "text", "name": "user_id", "nullable": false, "precision": undefined, "primary": false, "scale": undefined, "type": "text", "unsigned": false, }, }, "comment": undefined, "foreignKeys": { "session_user_id_foreign": { "columnNames": [ "user_id", ], "constraintName": "session_user_id_foreign", "deleteRule": "cascade", "localTableName": "session", "referencedColumnNames": [ "id", ], "referencedTableName": "user", "updateRule": "cascade", }, }, "indexes": [ { "columnNames": [ "user_id", ], "composite": false, "keyName": "session_user_id_index", "primary": false, "unique": false, }, { "columnNames": [ "session_token", ], "composite": false, "keyName": "session_session_token_unique", "primary": false, "unique": true, }, { "columnNames": [ "id", ], "composite": false, "expression": undefined, "keyName": "primary", "primary": true, "type": undefined, "unique": true, }, ], "name": "session", "schema": undefined, }, ], } `;
3,283
0
petrpan-code/nextauthjs/next-auth/packages/adapter-mongodb
petrpan-code/nextauthjs/next-auth/packages/adapter-mongodb/tests/custom.test.ts
import { runBasicTests } from "@auth/adapter-test" import { defaultCollections, format, MongoDBAdapter, _id } from "../src" import { MongoClient } from "mongodb" const name = "custom-test" const client = new MongoClient(`mongodb://localhost:27017/${name}`) const clientPromise = client.connect() const collections = { ...defaultCollections, Users: "some_userz" } runBasicTests({ adapter: MongoDBAdapter(clientPromise, { collections, }), db: { async disconnect() { await client.db().dropDatabase() await client.close() }, async user(id) { const user = await client .db() .collection(collections.Users) .findOne({ _id: _id(id) }) if (!user) return null return format.from(user) }, async account(provider_providerAccountId) { const account = await client .db() .collection(collections.Accounts) .findOne(provider_providerAccountId) if (!account) return null return format.from(account) }, async session(sessionToken) { const session = await client .db() .collection(collections.Sessions) .findOne({ sessionToken }) if (!session) return null return format.from(session) }, async verificationToken(identifier_token) { const token = await client .db() .collection(collections.VerificationTokens) .findOne(identifier_token) if (!token) return null const { _id, ...rest } = token return rest }, }, })
3,284
0
petrpan-code/nextauthjs/next-auth/packages/adapter-mongodb
petrpan-code/nextauthjs/next-auth/packages/adapter-mongodb/tests/index.test.ts
import { runBasicTests } from "@auth/adapter-test" import { defaultCollections, format, MongoDBAdapter, _id } from "../src" import { MongoClient } from "mongodb" const name = "test" const client = new MongoClient(`mongodb://localhost:27017/${name}`) const clientPromise = client.connect() runBasicTests({ adapter: MongoDBAdapter(clientPromise), db: { async disconnect() { await client.db().dropDatabase() await client.close() }, async user(id) { const user = await client .db() .collection(defaultCollections.Users) .findOne({ _id: _id(id) }) if (!user) return null return format.from(user) }, async account(provider_providerAccountId) { const account = await client .db() .collection(defaultCollections.Accounts) .findOne(provider_providerAccountId) if (!account) return null return format.from(account) }, async session(sessionToken) { const session = await client .db() .collection(defaultCollections.Sessions) .findOne({ sessionToken }) if (!session) return null return format.from(session) }, async verificationToken(identifier_token) { const token = await client .db() .collection(defaultCollections.VerificationTokens) .findOne(identifier_token) if (!token) return null const { _id, ...rest } = token return rest }, }, })
3,290
0
petrpan-code/nextauthjs/next-auth/packages/adapter-neo4j
petrpan-code/nextauthjs/next-auth/packages/adapter-neo4j/tests/index.test.ts
import * as neo4j from "neo4j-driver" import { runBasicTests } from "@auth/adapter-test" import statements from "./resources/statements" import { Neo4jAdapter, format } from "../src" globalThis.crypto ??= require("node:crypto").webcrypto const driver = neo4j.driver( "bolt://localhost", neo4j.auth.basic("neo4j", "password") ) const neo4jSession = driver.session() runBasicTests({ adapter: Neo4jAdapter(neo4jSession), db: { async connect() { for await (const statement of statements.split(";")) { if (!statement.length) return await neo4jSession.writeTransaction((tx) => tx.run(statement)) } }, async disconnect() { await neo4jSession.writeTransaction((tx) => tx.run( `MATCH (n) DETACH DELETE n RETURN count(n)` ) ) await neo4jSession.close() await driver.close() }, async user(id) { const result = await neo4jSession.readTransaction((tx) => tx.run(`MATCH (u:User) RETURN u`, { id }) ) return format.from(result?.records[0]?.get("u")?.properties) }, async session(sessionToken: string) { const result = await neo4jSession.readTransaction((tx) => tx.run( `MATCH (u:User)-[:HAS_SESSION]->(s:Session) RETURN s, u.id AS userId`, { sessionToken } ) ) const session = result?.records[0]?.get("s")?.properties const userId = result?.records[0]?.get("userId") if (!session || session.userId || !userId) return null return { ...format.from(session), userId } }, async account(provider_providerAccountId) { const result = await neo4jSession.readTransaction((tx) => tx.run( `MATCH (u:User)-[:HAS_ACCOUNT]->(a:Account) RETURN a, u.id AS userId`, provider_providerAccountId ) ) const account = result?.records[0]?.get("a")?.properties const userId = result?.records[0]?.get("userId") if (!account || account.userId || !userId) return null return { ...format.from(account), userId } }, async verificationToken(identifier_token) { const result = await neo4jSession.readTransaction((tx) => tx.run( `MATCH (v:VerificationToken) RETURN v`, identifier_token ) ) return format.from(result?.records[0]?.get("v")?.properties) }, }, })
3,298
0
petrpan-code/nextauthjs/next-auth/packages/adapter-pg
petrpan-code/nextauthjs/next-auth/packages/adapter-pg/tests/index.test.ts
import { runBasicTests } from "@auth/adapter-test" import PostgresAdapter, { mapExpiresAt } from "../src" import { Pool } from "pg" const POOL_SIZE = 20 const client = new Pool({ host: "127.0.0.1", database: "adapter-postgres-test", user: "pg", password: "pg", port: 5432, max: POOL_SIZE, }) runBasicTests({ adapter: PostgresAdapter(client), db: { disconnect: async () => { await client.end() }, user: async (id: string) => { const sql = `select * from users where id = $1` const result = await client.query(sql, [id]) return result.rowCount !== 0 ? result.rows[0] : null }, account: async (account) => { const sql = ` select * from accounts where "providerAccountId" = $1` const result = await client.query(sql, [account.providerAccountId]) return result.rowCount !== 0 ? mapExpiresAt(result.rows[0]) : null }, session: async (sessionToken) => { const result1 = await client.query( `select * from sessions where "sessionToken" = $1`, [sessionToken] ) return result1.rowCount !== 0 ? result1.rows[0] : null }, async verificationToken(identifier_token) { const { identifier, token } = identifier_token const sql = ` select * from verification_token where identifier = $1 and token = $2` const result = await client.query(sql, [identifier, token]) return result.rowCount !== 0 ? result.rows[0] : null }, }, })
3,304
0
petrpan-code/nextauthjs/next-auth/packages/adapter-pouchdb
petrpan-code/nextauthjs/next-auth/packages/adapter-pouchdb/tests/index.test.ts
import { runBasicTests } from "@auth/adapter-test" import { createIndexes, PouchDBAdapter, toAdapterAccount, toAdapterSession, toAdapterUser, toVerificationToken, } from "../src" import PouchDB from "pouchdb" import find from "pouchdb-find" import memoryAdapter from "pouchdb-adapter-memory" import { AdapterAccount, AdapterSession, AdapterUser, VerificationToken, } from "@auth/core/adapters" globalThis.crypto ??= require("node:crypto").webcrypto // pouchdb setup PouchDB.plugin(memoryAdapter).plugin(find) let pouchdb: PouchDB.Database let pouchdbIsDestroyed: boolean = false PouchDB.on("created", function () { pouchdbIsDestroyed = false }) PouchDB.on("destroyed", function () { pouchdbIsDestroyed = true }) const disconnect = async () => { if (!pouchdbIsDestroyed) await pouchdb.destroy() } pouchdb = new PouchDB(crypto.randomUUID(), { adapter: "memory" }) // Basic tests runBasicTests({ adapter: PouchDBAdapter({ pouchdb }), skipTests: ["deleteUser"], db: { async connect() { await createIndexes(pouchdb) }, disconnect, user: async (id) => { try { const res = await pouchdb.get<AdapterUser>(id) return toAdapterUser(res) } catch { return null } }, account: async ({ provider, providerAccountId }) => { const res = await ( pouchdb as unknown as PouchDB.Database<AdapterAccount> ).find({ use_index: "nextAuthAccountByProviderId", selector: { provider: { $eq: provider }, providerAccountId: { $eq: providerAccountId }, }, limit: 1, }) const doc = res.docs[0] return doc ? toAdapterAccount(doc) : null }, session: async (sessionToken) => { const res = await ( pouchdb as unknown as PouchDB.Database<AdapterSession> ).find({ use_index: "nextAuthSessionByToken", selector: { sessionToken: { $eq: sessionToken }, }, limit: 1, }) const doc = res.docs[0] return doc ? toAdapterSession(doc) : null }, async verificationToken({ identifier, token }) { const res = await ( pouchdb as unknown as PouchDB.Database<VerificationToken> ).find({ use_index: "nextAuthVerificationRequestByToken", selector: { identifier: { $eq: identifier }, token: { $eq: token }, }, limit: 1, }) const verificationRequest = res.docs[0] return toVerificationToken(verificationRequest) }, }, })
3,313
0
petrpan-code/nextauthjs/next-auth/packages/adapter-prisma
petrpan-code/nextauthjs/next-auth/packages/adapter-prisma/tests/index.test.ts
import { randomUUID, runBasicTests } from "@auth/adapter-test" import { PrismaClient } from "@prisma/client" import { PrismaAdapter } from "../src" import { ObjectId } from "mongodb" const prisma = new PrismaClient() runBasicTests({ adapter: PrismaAdapter(prisma), db: { id() { if (process.env.CONTAINER_NAME === "next-auth-mongodb-test") { return new ObjectId().toHexString() } return randomUUID() }, connect: async () => { await Promise.all([ prisma.user.deleteMany({}), prisma.account.deleteMany({}), prisma.session.deleteMany({}), prisma.verificationToken.deleteMany({}), ]) }, disconnect: async () => { await Promise.all([ prisma.user.deleteMany({}), prisma.account.deleteMany({}), prisma.session.deleteMany({}), prisma.verificationToken.deleteMany({}), ]) await prisma.$disconnect() }, user: (id) => prisma.user.findUnique({ where: { id } }), account: (provider_providerAccountId) => prisma.account.findUnique({ where: { provider_providerAccountId } }), session: (sessionToken) => prisma.session.findUnique({ where: { sessionToken } }), async verificationToken(identifier_token) { const result = await prisma.verificationToken.findUnique({ where: { identifier_token }, }) if (!result) return null // @ts-ignore // MongoDB needs an ID, but we don't delete result.id return result }, }, })
3,320
0
petrpan-code/nextauthjs/next-auth/packages/adapter-sequelize
petrpan-code/nextauthjs/next-auth/packages/adapter-sequelize/tests/index.test.ts
import { Sequelize, DataTypes } from "sequelize" import { runBasicTests } from "@auth/adapter-test" import SequelizeAdapter, { models } from "../src" const sequelize = new Sequelize({ logging: false, dialect: "sqlite", storage: ":memory:", }) runBasicTests({ adapter: SequelizeAdapter(sequelize), db: { connect: async () => { return await sequelize.sync({ force: true }) }, verificationToken: async (where) => { const verificationToken = await sequelize.models.verificationToken.findOne({ where }) return verificationToken?.get({ plain: true }) || null }, user: async (id) => { const user = await sequelize.models.user.findByPk(id) return user?.get({ plain: true }) || null }, account: async (where) => { const account = await sequelize.models.account.findOne({ where }) return account?.get({ plain: true }) || null }, session: async (sessionToken) => { const session = await sequelize.models.session.findOne({ where: { sessionToken }, }) return session?.get({ plain: true }) || null }, }, }) describe("Additional Sequelize tests", () => { describe("synchronize option", () => { const lowercase = (strs: string[]) => strs.map((s) => s.replace(/[^a-z]/gi, "").toLowerCase()) beforeEach(async () => { await sequelize.getQueryInterface().dropAllTables() const { getUser } = SequelizeAdapter(sequelize) await getUser("1") }) test("Creates DB tables", async () => { const tables = await sequelize.getQueryInterface().showAllSchemas() expect(tables).toEqual([ { name: "users" }, { name: "accounts" }, { name: "sessions" }, { name: "verification_tokens" }, ]) }) test("Correctly creates users table", async () => { const table = await sequelize.getQueryInterface().describeTable("users") expect(lowercase(Object.keys(table))).toEqual( lowercase(Object.keys(models.User)) ) }) test("Correctly creates accounts table", async () => { const table = await sequelize .getQueryInterface() .describeTable("accounts") expect(lowercase(Object.keys(table))).toEqual( lowercase(Object.keys(models.Account)) ) }) test("Correctly creates sessions table", async () => { const table = await sequelize .getQueryInterface() .describeTable("sessions") expect(lowercase(Object.keys(table))).toEqual( lowercase(Object.keys(models.Session)) ) }) test("Correctly creates verification_tokens table", async () => { const table = await sequelize .getQueryInterface() .describeTable("verification_tokens") expect(lowercase(Object.keys(table))).toEqual( lowercase(Object.keys(models.VerificationToken)) ) }) }) describe("overriding models", () => { beforeEach(async () => { await sequelize.getQueryInterface().dropAllTables() const { getUser } = SequelizeAdapter(sequelize, { synchronize: true, models: { User: sequelize.define("users", { ...models.User, someUserAttribute: { type: DataTypes.STRING }, }), Account: sequelize.define("accounts", { ...models.Account, someAccountAttribute: { type: DataTypes.STRING }, }), Session: sequelize.define("sessions", { ...models.Session, someSessionAttribute: { type: DataTypes.STRING }, }), VerificationToken: sequelize.define("verification_tokens", { ...models.VerificationToken, someVerificationTokenAttribute: { type: DataTypes.STRING }, }), }, }) await getUser("1") }) test("Custom user model", async () => { const table = await sequelize.getQueryInterface().describeTable("users") expect(table.someUserAttribute).toBeDefined() }) test("Custom account model", async () => { const table = await sequelize .getQueryInterface() .describeTable("accounts") expect(table.someAccountAttribute).toBeDefined() }) test("Custom session model", async () => { const table = await sequelize .getQueryInterface() .describeTable("sessions") expect(table.someSessionAttribute).toBeDefined() }) test("Custom verification_token model", async () => { const table = await sequelize .getQueryInterface() .describeTable("verification_tokens") expect(table.someVerificationTokenAttribute).toBeDefined() }) }) })
3,329
0
petrpan-code/nextauthjs/next-auth/packages/adapter-supabase
petrpan-code/nextauthjs/next-auth/packages/adapter-supabase/tests/index.test.ts
import { runBasicTests } from "@auth/adapter-test" import { format, SupabaseAdapter } from "../src" import { createClient } from "@supabase/supabase-js" import type { AdapterSession, AdapterUser, VerificationToken, } from "@auth/core/adapters" import type { Account } from "@auth/core/types" const url = process.env.SUPABASE_URL ?? "http://localhost:54321" const secret = process.env.SUPABASE_SERVICE_ROLE_KEY || "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6InNlcnZpY2Vfcm9sZSJ9.vI9obAHOGyVVKa3pD--kJlyxp-Z2zV9UUMAhKpNLAcU" const supabase = createClient(url, secret, { db: { schema: "next_auth" } }) runBasicTests({ adapter: SupabaseAdapter({ url, secret }), db: { async session(sessionToken) { const { data, error } = await supabase .from("sessions") .select() .eq("sessionToken", sessionToken) .maybeSingle() if (error) throw error if (!data) return null return format<AdapterSession>(data) }, async user(id) { const { data, error } = await supabase .from("users") .select() .eq("id", id) .maybeSingle() if (error) throw error if (!data) return null return format<AdapterUser>(data) }, async account({ provider, providerAccountId }) { const { data, error } = await supabase .from("accounts") .select() .match({ provider, providerAccountId }) .maybeSingle() if (error) throw error if (!data) return null return format<Account>(data) }, async verificationToken({ identifier, token }) { const { data, error } = await supabase .from("verification_tokens") .select() .match({ identifier, token }) .single() if (error) throw error const { id, ...verificationToken } = data return format<VerificationToken>(verificationToken) }, }, })
3,336
0
petrpan-code/nextauthjs/next-auth/packages/adapter-surrealdb
petrpan-code/nextauthjs/next-auth/packages/adapter-surrealdb/tests/index.test.ts
import Surreal, { ExperimentalSurrealHTTP } from "surrealdb.js" import { runBasicTests } from "@auth/adapter-test" import { config } from "./common" const clientPromise = new Promise<Surreal>(async (resolve, reject) => { const db = new Surreal() try { await db.connect("http://0.0.0.0:8000/rpc", { ns: "test", db: "test", auth: { user: "test", pass: "test", }, }) resolve(db) } catch (e) { reject(e) } }) runBasicTests(config(clientPromise)) const clientPromiseRest = new Promise<ExperimentalSurrealHTTP<typeof fetch>>( async (resolve, reject) => { try { const db = new ExperimentalSurrealHTTP("http://0.0.0.0:8000", { fetch, auth: { user: "test", pass: "test", }, ns: "test", db: "test", }) resolve(db) } catch (e) { reject(e) } } ) runBasicTests(config(clientPromiseRest))
3,350
0
petrpan-code/nextauthjs/next-auth/packages/adapter-typeorm
petrpan-code/nextauthjs/next-auth/packages/adapter-typeorm/tests/index.test.ts
import { parseDataSourceConfig } from "../src/utils" const connectionString = "mysql://root:password@localhost:3306/next-auth" test("could parse connection string", () => { expect(parseDataSourceConfig(connectionString)).toEqual( expect.objectContaining({ type: "mysql", host: "localhost", port: 3306, username: "root", password: "password", database: "next-auth", }) ) })
3,353
0
petrpan-code/nextauthjs/next-auth/packages/adapter-typeorm/tests
petrpan-code/nextauthjs/next-auth/packages/adapter-typeorm/tests/mysql/index.custom.test.ts
import { runBasicTests } from "../../../adapter-test" import { TypeORMAdapter } from "../../src" import * as entities from "../custom-entities" import { db } from "../helpers" import { SnakeNamingStrategy } from "typeorm-naming-strategies" import type { ConnectionOptions } from "typeorm" const mysqlConfig: ConnectionOptions = { type: "mysql" as const, host: "localhost", port: 3306, username: "root", password: "password", database: "next-auth", synchronize: true, namingStrategy: new SnakeNamingStrategy(), } runBasicTests({ adapter: TypeORMAdapter(mysqlConfig, { entities, }), db: db(mysqlConfig, entities), })
3,354
0
petrpan-code/nextauthjs/next-auth/packages/adapter-typeorm/tests
petrpan-code/nextauthjs/next-auth/packages/adapter-typeorm/tests/mysql/index.test.ts
import { runBasicTests } from "../../../adapter-test" import { TypeORMAdapter } from "../../src" import { db } from "../helpers" const mysqlConfig = { type: "mysql" as const, host: "localhost", port: 3306, username: "root", password: "password", database: "next-auth", synchronize: true, } runBasicTests({ adapter: TypeORMAdapter(mysqlConfig), db: db(mysqlConfig), })
3,356
0
petrpan-code/nextauthjs/next-auth/packages/adapter-typeorm/tests
petrpan-code/nextauthjs/next-auth/packages/adapter-typeorm/tests/postgresql/index.custom.test.ts
import { runBasicTests } from "../../../adapter-test" import { TypeORMAdapter } from "../../src" import * as entities from "../custom-entities" import { db } from "../helpers" const postgresConfig = "postgres://nextauth:password@localhost:5432/nextauth?synchronize=true" runBasicTests({ adapter: TypeORMAdapter(postgresConfig, { entities, }), db: db(postgresConfig, entities), })
3,357
0
petrpan-code/nextauthjs/next-auth/packages/adapter-typeorm/tests
petrpan-code/nextauthjs/next-auth/packages/adapter-typeorm/tests/postgresql/index.test.ts
import { runBasicTests } from "../../../adapter-test" import { TypeORMAdapter } from "../../src" import { db } from "../helpers" const postgresConfig = "postgres://nextauth:password@localhost:5432/nextauth?synchronize=true" runBasicTests({ adapter: TypeORMAdapter(postgresConfig), db: db(postgresConfig), })
3,359
0
petrpan-code/nextauthjs/next-auth/packages/adapter-typeorm/tests
petrpan-code/nextauthjs/next-auth/packages/adapter-typeorm/tests/sqlite/index.custom.test.ts
import { runBasicTests } from "../../../adapter-test" import { TypeORMAdapter } from "../../src" import * as entities from "../custom-entities" import { db } from "../helpers" const sqliteConfig = { type: "sqlite" as const, name: "next-auth-test-memory", database: "./tests/sqlite/dev.db", synchronize: true, } runBasicTests({ adapter: TypeORMAdapter(sqliteConfig, { entities, }), db: db(sqliteConfig, entities), })
3,360
0
petrpan-code/nextauthjs/next-auth/packages/adapter-typeorm/tests
petrpan-code/nextauthjs/next-auth/packages/adapter-typeorm/tests/sqlite/index.test.ts
import { runBasicTests } from "../../../adapter-test" import { TypeORMAdapter } from "../../src" import { db } from "../helpers" import { SnakeNamingStrategy } from "typeorm-naming-strategies" import type { DataSourceOptions } from "typeorm" const sqliteConfig: DataSourceOptions = { type: "sqlite" as const, name: "next-auth-test-memory", database: "./tests/sqlite/dev.db", synchronize: true, namingStrategy: new SnakeNamingStrategy(), } runBasicTests({ adapter: TypeORMAdapter(sqliteConfig), db: db(sqliteConfig), })
3,367
0
petrpan-code/nextauthjs/next-auth/packages/adapter-upstash-redis
petrpan-code/nextauthjs/next-auth/packages/adapter-upstash-redis/tests/index.test.ts
import { Redis } from "@upstash/redis" import { runBasicTests } from "@auth/adapter-test" import { hydrateDates, UpstashRedisAdapter } from "../src" import "dotenv/config" globalThis.crypto ??= require("node:crypto").webcrypto if (!process.env.UPSTASH_REDIS_URL || !process.env.UPSTASH_REDIS_KEY) { test("Skipping UpstashRedisAdapter tests, since required environment variables aren't available", () => { expect(true).toBe(true) }) process.exit(0) } if (process.env.CI) { // TODO: Fix this test('Skipping UpstashRedisAdapter tests in CI because of "Request failed" errors. Should revisit', () => { expect(true).toBe(true) }) process.exit(0) } const client = new Redis({ url: process.env.UPSTASH_REDIS_URL, token: process.env.UPSTASH_REDIS_KEY, }) runBasicTests({ adapter: UpstashRedisAdapter(client, { baseKeyPrefix: "testApp:" }), db: { disconnect: client.flushdb, async user(id: string) { const data = await client.get<object>(`testApp:user:${id}`) if (!data) return null return hydrateDates(data) }, async account({ provider, providerAccountId }) { const data = await client.get<object>( `testApp:user:account:${provider}:${providerAccountId}` ) if (!data) return null return hydrateDates(data) }, async session(sessionToken) { const data = await client.get<object>( `testApp:user:session:${sessionToken}` ) if (!data) return null return hydrateDates(data) }, async verificationToken(where) { const data = await client.get<object>( `testApp:user:token:${where.identifier}:${where.token}` ) if (!data) return null return hydrateDates(data) }, }, })
3,373
0
petrpan-code/nextauthjs/next-auth/packages/adapter-xata
petrpan-code/nextauthjs/next-auth/packages/adapter-xata/tests/index.test.ts
import { runBasicTests } from "@auth/adapter-test" import "dotenv/config" import { XataClient } from "../src/xata" import { XataAdapter } from "../src" if (!process.env.XATA_API_KEY) { test("Skipping XataAdapter tests, since required environment variables aren't available", () => { expect(true).toBe(true) }) process.exit(0) } if (process.env.CI) { // TODO: Fix this test('Skipping XataAdapter tests in CI because of "Request failed" errors. Should revisit', () => { expect(true).toBe(true) }) process.exit(0) } const client = new XataClient({ apiKey: process.env.XATA_API_KEY, }) runBasicTests({ adapter: XataAdapter(client), db: { async user(id: string) { const data = await client.db.nextauth_users.filter({ id }).getFirst() if (!data) return null return data }, async account({ provider, providerAccountId }) { const data = await client.db.nextauth_accounts .filter({ provider, providerAccountId }) .getFirst() if (!data) return null return data }, async session(sessionToken) { const data = await client.db.nextauth_sessions .filter({ sessionToken }) .getFirst() if (!data) return null return data }, async verificationToken(where) { const data = await client.db.nextauth_verificationTokens .filter(where) .getFirst() if (!data) return null return data }, }, })
3,506
0
petrpan-code/nextauthjs/next-auth/packages/frameworks-sveltekit
petrpan-code/nextauthjs/next-auth/packages/frameworks-sveltekit/tests/test.ts
import { expect, test } from "@playwright/test" test("index page has expected h1", async ({ page }) => { await page.goto("/") expect(await page.textContent("h1")).toBe("Welcome to SvelteKit") })
4,395
0
petrpan-code/GeekyAnts/NativeBase/src/components/composites/FormControl
petrpan-code/GeekyAnts/NativeBase/src/components/composites/FormControl/test/FormControl.test.tsx
import React from 'react'; import { FormControl, useFormControl } from '../index'; import { TextInput } from 'react-native'; import { render } from '@testing-library/react-native'; import { Wrapper } from '../../../../utils/test-utils'; const Input = React.forwardRef((props: any, ref: any) => { const inputProps = useFormControl(props); return ( //@ts-ignore <TextInput ref={ref} {...inputProps} /> ); }); it('a11y test in when required', async () => { let { getByPlaceholderText } = render( <Wrapper> <FormControl nativeID="name" isRequired> <FormControl.Label>Name</FormControl.Label> <Input placeholder="Name" /> <FormControl.HelperText>Enter your name please!</FormControl.HelperText> <FormControl.ErrorMessage> Your name is invalid </FormControl.ErrorMessage> </FormControl> </Wrapper> ); const textInput = getByPlaceholderText('Name'); expect(textInput.props.accessibilityRequired).toBe(true); expect(textInput.props.required).toBe(true); }); it('a11y test in when invalid', async () => { let { getByPlaceholderText } = render( <Wrapper> <FormControl nativeID="name" isInvalid> <FormControl.Label>Name</FormControl.Label> <Input placeholder="Name" /> <FormControl.HelperText>Enter your name please!</FormControl.HelperText> <FormControl.ErrorMessage> Your name is invalid </FormControl.ErrorMessage> </FormControl> </Wrapper> ); const textInput = getByPlaceholderText('Name'); expect(textInput.props.accessibilityInvalid).toBe(true); }); it('a11y test in when readOnly', async () => { let { getByPlaceholderText } = render( <Wrapper> <FormControl nativeID="name" isReadOnly> <FormControl.Label>Name</FormControl.Label> <Input placeholder="Name" /> <FormControl.HelperText>Enter your name please!</FormControl.HelperText> <FormControl.ErrorMessage> Your name is invalid </FormControl.ErrorMessage> </FormControl> </Wrapper> ); const textInput = getByPlaceholderText('Name'); expect(textInput.props.accessibilityReadOnly).toBe(true); expect(textInput.props.readOnly).toBe(true); }); it('a11y test in when disabled', async () => { let { getByPlaceholderText } = render( <Wrapper> <FormControl nativeID="name" isDisabled> <FormControl.Label>Name</FormControl.Label> <Input placeholder="Name" /> <FormControl.HelperText>Enter your name please!</FormControl.HelperText> <FormControl.ErrorMessage> Your name is invalid </FormControl.ErrorMessage> </FormControl> </Wrapper> ); const textInput = getByPlaceholderText('Name'); expect(textInput.props.disabled).toBe(true); }); it('a11y test when helper text is present', async () => { let { getByPlaceholderText } = render( <Wrapper> <FormControl nativeID="name" isDisabled> <FormControl.Label>Name</FormControl.Label> <Input placeholder="Name" /> <FormControl.HelperText>Enter your name please!</FormControl.HelperText> </FormControl> </Wrapper> ); const textInput = getByPlaceholderText('Name'); expect(textInput.props.accessibilityDescribedBy).toBe('name-helptext'); expect(textInput.props.accessibilityReadOnly).toBeUndefined(); expect(textInput.props.accessibilityInvalid).toBeUndefined(); expect(textInput.props.accessibilityRequired).toBeUndefined(); }); it('sets htmlFor of FormLabel ref to nativeID of Input', async () => { let ref: HTMLLabelElement; const inputID = 'name'; let { getByPlaceholderText } = render( <Wrapper> <FormControl nativeID={inputID} isInvalid> <FormControl.Label //@ts-ignore ref={(_ref) => (ref = _ref)} > Name </FormControl.Label> <Input placeholder="Name" /> <FormControl.HelperText>Enter your name please!</FormControl.HelperText> <FormControl.ErrorMessage> Your name is invalid </FormControl.ErrorMessage> </FormControl> </Wrapper> ); const textInput = getByPlaceholderText('Name'); //@ts-ignore expect(textInput.props.nativeID).toBe(ref.htmlFor); });
4,507
0
petrpan-code/GeekyAnts/NativeBase/src/components/primitives/Checkbox
petrpan-code/GeekyAnts/NativeBase/src/components/primitives/Checkbox/test/checkbox.test.tsx
import React from 'react'; import { fireEvent, render } from '@testing-library/react-native'; import { NativeBaseProvider } from '../../../../core/NativeBaseProvider'; import { Checkbox } from '..'; import { Text } from '../..'; function CheckBoxGroup() { const [groupValue, setGroupValue] = React.useState(['Item 1 ', 'Item 3 ']); return ( <Checkbox.Group colorScheme="green" defaultValue={groupValue} onChange={(values) => { setGroupValue(values || []); }} > <Checkbox value="Item 1 "> <Text mx={2}>Item 1</Text> </Checkbox> <Checkbox value="Item 2 "> <Text mx={2}>Item 2</Text> </Checkbox> <Checkbox value="Item 3 "> <Text mx={2}>Item 3</Text> </Checkbox> <Checkbox colorScheme="orange" value="Indeterminate Item "> <Text mx={2}>Indeterminate Item</Text> </Checkbox> </Checkbox.Group> ); } function CheckBox(group: any) { const [groupValues, setGroupValues] = React.useState<Array<any>>([]); return group ? ( <Checkbox.Group onChange={setGroupValues} value={groupValues}> <Checkbox value="one"> <Text>One</Text> </Checkbox> <Checkbox value="two" isIndeterminate onChange={() => setGroupValues([...groupValues, 'two'])} > <Text>Two</Text> </Checkbox> </Checkbox.Group> ) : ( <> <Checkbox value="one" onChange={() => { setGroupValues([...groupValues, 'one']); }} > <Text>One</Text> </Checkbox> <Checkbox value="two" isIndeterminate onChange={() => setGroupValues([...groupValues, 'two'])} > <Text>Two</Text> </Checkbox> </> ); } describe('CheckBoxGroup', () => { it('handles defaults and onChange on checkBoxGroup', () => { const { getAllByRole } = render( <NativeBaseProvider initialWindowMetrics={{ frame: { x: 0, y: 0, width: 0, height: 0 }, insets: { top: 0, left: 0, right: 0, bottom: 0 }, }} > <CheckBoxGroup /> </NativeBaseProvider> ); const checkbox = getAllByRole('checkbox'); expect(checkbox.length).toBe(4); expect(checkbox[0].props.accessibilityState.checked).toBe(true); expect(checkbox[1].props.accessibilityState.checked).toBe(false); expect(checkbox[2].props.accessibilityState.checked).toBe(true); expect(checkbox[3].props.accessibilityState.checked).toBe(false); fireEvent.press(checkbox[1]); expect(checkbox[1].props.accessibilityState.checked).toBe(true); }); it('can be disabled on checkBox', () => { const { getAllByRole } = render( <NativeBaseProvider initialWindowMetrics={{ frame: { x: 0, y: 0, width: 0, height: 0 }, insets: { top: 0, left: 0, right: 0, bottom: 0 }, }} > <Checkbox value="Item 1 "> <Text mx={2}>Item 1</Text> </Checkbox> <Checkbox value="Item 2 " isDisabled> <Text mx={2}>Item 2</Text> </Checkbox> <Checkbox value="Item 3 "> <Text mx={2}>Item 3</Text> </Checkbox> <Checkbox colorScheme="orange" value="Indeterminate Item "> <Text mx={2}>Indeterminate Item</Text> </Checkbox> </NativeBaseProvider> ); const checkbox = getAllByRole('checkbox'); expect(checkbox.length).toBe(4); expect(checkbox[1].props.accessibilityState.disabled).toBe(true); }); it('is checked on checkBox', () => { const { getAllByRole } = render( <NativeBaseProvider initialWindowMetrics={{ frame: { x: 0, y: 0, width: 0, height: 0 }, insets: { top: 0, left: 0, right: 0, bottom: 0 }, }} > <Checkbox value="Item 1 " isChecked> <Text mx={2}>Item 1</Text> </Checkbox> <Checkbox value="Item 2 " isDisabled> <Text mx={2}>Item 2</Text> </Checkbox> <Checkbox value="Item 3 "> <Text mx={2}>Item 3</Text> </Checkbox> <Checkbox colorScheme="orange" value="Indeterminate Item "> <Text mx={2}>Indeterminate Item</Text> </Checkbox> </NativeBaseProvider> ); const checkbox = getAllByRole('checkbox'); expect(checkbox.length).toBe(4); expect(checkbox[0].props.accessibilityState.checked).toBe(true); }); /**** inDeterminant is not yet implemented in checkbox ****/ // it('inDeterminant on checkBoxGroup', () => { // const { getAllByRole } = render( // <NativeBaseProvider // initialWindowMetrics={{ // frame: { x: 0, y: 0, width: 0, height: 0 }, // insets: { top: 0, left: 0, right: 0, bottom: 0 }, // }} // > // <CheckBox group={true} /> // </NativeBaseProvider> // ); // const checkbox = getAllByRole('checkbox'); // expect(checkbox.length).toBe(2); // expect(checkbox[1].props.accessibilityState.checked).toBe('mixed'); // }); // it('inDeterminant on checkBox', () => { // const { getAllByRole } = render( // <NativeBaseProvider // initialWindowMetrics={{ // frame: { x: 0, y: 0, width: 0, height: 0 }, // insets: { top: 0, left: 0, right: 0, bottom: 0 }, // }} // > // <CheckBox group={false} /> // </NativeBaseProvider> // ); // const checkbox = getAllByRole('checkbox'); // expect(checkbox.length).toBe(2); // fireEvent.press(checkbox[1]); // expect(checkbox[1].props.accessibilityState.checked).toBe('mixed'); // }); it('onChange on checkBox', () => { const { getAllByRole } = render( <NativeBaseProvider initialWindowMetrics={{ frame: { x: 0, y: 0, width: 0, height: 0 }, insets: { top: 0, left: 0, right: 0, bottom: 0 }, }} > <CheckBox /> </NativeBaseProvider> ); const checkbox = getAllByRole('checkbox'); expect(checkbox.length).toBe(2); fireEvent.press(checkbox[0]); expect(checkbox[0].props.accessibilityState.checked).toBe(true); }); });
4,577
0
petrpan-code/GeekyAnts/NativeBase/src/components/primitives/Radio
petrpan-code/GeekyAnts/NativeBase/src/components/primitives/Radio/test/radio.test.tsx
import React from 'react'; import { fireEvent, render } from '@testing-library/react-native'; import { Radio } from '..'; import { Text } from '../..'; import { NativeBaseProvider } from '../../../../core/NativeBaseProvider'; function RadiosGroup() { const [, setValue] = React.useState<any>('one'); return ( <Radio.Group defaultValue="1" name="myRadioGroup" onChange={(nextValue: any) => { setValue(nextValue); }} > <Radio value="1"> <Text mx={2}>First</Text> </Radio> <Radio value="2"> <Text mx={2}>Second</Text> </Radio> <Radio value="3"> <Text mx={2}>Third</Text> </Radio> </Radio.Group> ); } describe('RadioGroup', () => { it('onChange and default on RadioGroup', () => { let { getAllByRole, getByText } = render( <NativeBaseProvider initialWindowMetrics={{ frame: { x: 0, y: 0, width: 0, height: 0 }, insets: { top: 0, left: 0, right: 0, bottom: 0 }, }} > <RadiosGroup /> </NativeBaseProvider> ); let radios = getAllByRole('radio'); expect(radios.length).toBe(3); expect(radios[0].props.accessibilityState.checked).toBe(true); expect(radios[1].props.accessibilityState.checked).toBe(false); expect(radios[2].props.accessibilityState.checked).toBe(false); let second = getByText('Second'); fireEvent.press(second); expect(radios[0].props.accessibilityState.checked).toBe(false); }); it('can be disabled', () => { let { getAllByRole } = render( <NativeBaseProvider initialWindowMetrics={{ frame: { x: 0, y: 0, width: 0, height: 0 }, insets: { top: 0, left: 0, right: 0, bottom: 0 }, }} > <Radio.Group defaultValue="1" name="myRadioGroup"> <Radio value="1"> <Text mx={2}>First</Text> </Radio> <Radio value="2" isDisabled> <Text mx={2}>Second</Text> </Radio> <Radio value="3"> <Text mx={2}>Third</Text> </Radio> </Radio.Group> </NativeBaseProvider> ); let second = getAllByRole('radio'); expect(second[1].props.accessibilityState.disabled).toBe(true); }); });
4,605
0
petrpan-code/GeekyAnts/NativeBase/src/components/primitives/Switch
petrpan-code/GeekyAnts/NativeBase/src/components/primitives/Switch/test/switch.test.tsx
import React from 'react'; import { render } from '@testing-library/react-native'; import { NativeBaseProvider } from '../../../../core/NativeBaseProvider'; import Switch from '../index'; jest.useFakeTimers(); describe('Switch', () => { it('can be default checked', () => { let { getAllByRole } = render( <NativeBaseProvider initialWindowMetrics={{ frame: { x: 0, y: 0, width: 0, height: 0 }, insets: { top: 0, left: 0, right: 0, bottom: 0 }, }} > <Switch defaultIsChecked /> </NativeBaseProvider> ); let switches = getAllByRole('switch'); expect(switches[0].props.value).toBe(true); }); it('can be disabled', () => { let { getAllByRole } = render( <NativeBaseProvider initialWindowMetrics={{ frame: { x: 0, y: 0, width: 0, height: 0 }, insets: { top: 0, left: 0, right: 0, bottom: 0 }, }} > <Switch isDisabled /> </NativeBaseProvider> ); let switches = getAllByRole('switch'); expect(switches[0].props.disabled).toBe(true); }); });
4,608
0
petrpan-code/GeekyAnts/NativeBase/src/components/primitives/Text
petrpan-code/GeekyAnts/NativeBase/src/components/primitives/Text/__test__/Text.test.tsx
/** * @jest-environment jsdom */ //@ts-nocheck import React from 'react'; import { render } from '@testing-library/react-native'; import Text from '../../Text'; import { NativeBaseProvider } from '../../../../core/NativeBaseProvider'; import { theme as defaultTheme } from '../../../../theme'; import { Platform } from 'react-native'; jest.useFakeTimers(); const theme = { ...defaultTheme, fontConfig: { Roboto: { 100: 'Roboto-Light', 200: 'Roboto-Light', 300: 'Roboto-Light', 400: { normal: 'Roboto-Regular', italic: 'Roboto-Italic', }, 500: 'Roboto-Medium', 600: 'Roboto-Medium', 700: { normal: 'Roboto-Bold', italic: 'Roboto-BoldItalic', }, 800: 'Roboto-Bold', 900: 'Roboto-Black', }, }, fonts: { ...defaultTheme.fonts, heading: 'Roboto', body: 'Roboto', }, }; const Provider = (props: any) => { return ( <NativeBaseProvider theme={theme} {...props} initialWindowMetrics={{ frame: { x: 0, y: 0, width: 0, height: 0 }, insets: { top: 0, left: 0, right: 0, bottom: 0 }, }} /> ); }; describe('Text component', () => { it('resolves default custom fonts', () => { const { getByTestId } = render( <Provider> <Text testID="my-text">hello world</Text> </Provider> ); const text = getByTestId('my-text'); expect(text.props.style.fontFamily).toBe('Roboto-Regular'); }); it('resolves custom font variants', () => { const { getByTestId } = render( <Provider> <Text testID="my-text" fontStyle="italic"> hello world </Text> </Provider> ); const text = getByTestId('my-text'); expect(text.props.style.fontFamily).toBe('Roboto-Italic'); }); it('resolves to bold italic font', () => { const { getByTestId } = render( <Provider> <Text testID="my-text" fontWeight="bold" fontStyle="italic"> hello world </Text> </Provider> ); const text = getByTestId('my-text'); expect(text.props.style.fontFamily).toBe('Roboto-BoldItalic'); }); it('resolves to medium font when fontWeight is 500', () => { const { getByTestId } = render( <Provider> <Text testID="my-text" fontWeight={500}> hello world </Text> </Provider> ); const text = getByTestId('my-text'); expect(text.props.style.fontFamily).toBe('Roboto-Medium'); }); it('resolves to medium font when fontWeight is medium', () => { const { getByTestId } = render( <Provider> <Text testID="my-text" fontWeight={'medium'}> hello world </Text> </Provider> ); const text = getByTestId('my-text'); expect(text.props.style.fontFamily).toBe('Roboto-Medium'); }); it('respects fontFamily property', () => { const { getByTestId } = render( <Provider> <Text testID="my-text" fontFamily="Merriweather-Italic"> hello world </Text> </Provider> ); const text = getByTestId('my-text'); expect(text.props.style.fontFamily).toBe('Merriweather-Italic'); }); it("doesn't break if custom font is not specified", () => { const newTheme = JSON.parse(JSON.stringify(defaultTheme)); delete newTheme.fontConfig; const { getByTestId } = render( <Provider theme={newTheme}> <Text testID="my-text" fontWeight={400}> hello world </Text> </Provider> ); const text = getByTestId('my-text'); expect(text.props.style.fontFamily).toBe(undefined); }); it("doesn't pass fontWeight and fontStyle if a custom fontFamily is resolved", () => { const { getByTestId } = render( <Provider> <Text testID="my-text" fontWeight={400}> hello world </Text> </Provider> ); const text = getByTestId('my-text'); expect(text.props.style.fontWeight).toBe(undefined); expect(text.props.style.fontStyle).toBe(undefined); expect(text.props.style.fontFamily).toBe('Roboto-Regular'); }); it('tests lineHeight from token in text ', () => { const { getByTestId } = render( <Provider> <Text lineHeight="md" testID="test"> This is a text </Text> </Provider> ); const text = getByTestId('test'); expect(text.props.style.lineHeight).toBe( defaultTheme.fontSizes.sm * parseFloat(defaultTheme.lineHeights.md) ); }); it('tests absolute lineHeight in text ', () => { const { getByTestId } = render( <Provider> <Text lineHeight={5} testID="test"> This is a text </Text> </Provider> ); const text = getByTestId('test'); expect(text.props.style.lineHeight).toBe(5); }); it('tests em non token lineHeight in text ', () => { const { getByTestId } = render( <Provider> <Text lineHeight="13em" testID="test"> This is a text </Text> </Provider> ); const text = getByTestId('test'); expect(text.props.style.lineHeight).toBe(defaultTheme.fontSizes.sm * 13); }); it('tests letterSpacing from token in text ', () => { const { getByTestId } = render( <Provider> <Text letterSpacing="2xl" testID="test"> This is a text </Text> </Provider> ); const text = getByTestId('test'); expect(text.props.style.letterSpacing).toBe( defaultTheme.fontSizes.sm * parseFloat(defaultTheme.letterSpacings['2xl']) ); }); it('tests letterSpacing in em from token in text ', () => { Platform.OS = 'web'; try { render( <Provider> <Text letterSpacing="2xl" testID="test"> This is a text </Text> </Provider> ); } catch (e) { expect(e.message).toContain(`"letterSpacing": "0.1em"`); } finally { Platform.OS = 'ios'; } }); it('tests lineHeight and letterSpacing in px', () => { const { getByTestId } = render( <Provider> <Text lineHeight="24px" letterSpacing="12px" testID="test"> This is a text </Text> </Provider> ); const text = getByTestId('test'); expect(text.props.style.lineHeight).toBe(24); expect(text.props.style.letterSpacing).toBe(12); }); });
4,655
0
petrpan-code/GeekyAnts/NativeBase/src/hooks
petrpan-code/GeekyAnts/NativeBase/src/hooks/tests/useBreakpointValue.test.tsx
import React from 'react'; import { useBreakpointValue } from '../../hooks/useBreakpointValue'; import { NativeBaseProvider } from '../../core/NativeBaseProvider'; import { renderHook } from '@testing-library/react-hooks'; describe('useBreakpointValue', () => { const wrapper = ({ children }: any) => ( <NativeBaseProvider initialWindowMetrics={{ frame: { x: 0, y: 0, width: 0, height: 0 }, insets: { top: 0, left: 0, right: 0, bottom: 0 }, }} > {children} </NativeBaseProvider> ); test('Empty array', () => { const { result } = renderHook(() => useBreakpointValue([]), { wrapper, }); expect(result.current).toEqual([]); }); test('Empty object', () => { const { result } = renderHook(() => useBreakpointValue({}), { wrapper, }); expect(result.current).toEqual(undefined); }); test('Basic array', () => { const { result } = renderHook(() => useBreakpointValue([1, 2, 3]), { wrapper, }); expect(result.current).toEqual(2); }); test('Basic Object', () => { const { result } = renderHook( () => useBreakpointValue({ base: 0, sm: 1, md: 2 }), { wrapper, } ); expect(result.current).toEqual(1); }); });
4,663
0
petrpan-code/GeekyAnts/NativeBase/src/hooks
petrpan-code/GeekyAnts/NativeBase/src/hooks/useThemeProps/usePropsResolution.test.tsx
import React from 'react'; import { render } from '@testing-library/react-native'; import { theme as defaultTheme } from '../../theme'; import { NativeBaseProvider } from '../../core/NativeBaseProvider'; import { Box, Button, Pressable, // Select, Image, Spinner, Text, Input, Checkbox, Slider, // Icon, HStack, Heading, } from '../../components/primitives'; // import { Ionicons } from '@expo/vector-icons'; import { FormControl, Menu } from '../../components/composites'; import { Platform } from 'react-native'; import { extendTheme } from '../../core/extendTheme'; import { fireEvent } from '@testing-library/react-native'; // import { InfoIcon } from '../../components/primitives/Icon/Icons'; const inset = { frame: { x: 0, y: 0, width: 0, height: 0 }, insets: { top: 0, left: 0, right: 0, bottom: 0 }, }; const Provider = ({ children, theme = defaultTheme }: any) => { return ( <NativeBaseProvider initialWindowMetrics={inset} theme={theme}> {children} </NativeBaseProvider> ); }; function CheckBoxGroup() { const [groupValue, setGroupValue] = React.useState(['Item 1 ', 'Item 3 ']); return ( <Checkbox.Group colorScheme="green" defaultValue={groupValue} onChange={(values) => { setGroupValue(values || []); }} > <Checkbox value="Item 1 "> <Text mx={2}>Item 1</Text> </Checkbox> <Checkbox value="Item 2 "> <Text mx={2}>Item 2</Text> </Checkbox> <Checkbox value="Item 3 "> <Text mx={2}>Item 3</Text> </Checkbox> <Checkbox colorScheme="orange" value="Indeterminate Item "> <Text mx={2}>Indeterminate Item</Text> </Checkbox> </Checkbox.Group> ); } describe('props resolution', () => { it('tests simple resolution', () => { const { getByTestId } = render( <Provider> <Box p={2} testID="test"> hello world </Box> </Provider> ); const box = getByTestId('test'); expect(box.props.style.paddingLeft).toBe(defaultTheme.space['2']); expect(box.props.style.paddingRight).toBe(defaultTheme.space['2']); expect(box.props.style.paddingTop).toBe(defaultTheme.space['2']); expect(box.props.style.paddingBottom).toBe(defaultTheme.space['2']); }); it('tests simple resolution with responsive props', () => { const { getByTestId } = render( <Provider> <Box p={[2, 4, 5]} testID="test"> hello world </Box> <Box p={{ base: 1, sm: 5, lg: 10 }} testID="test2"> hello world </Box> </Provider> ); const box = getByTestId('test'); expect(box.props.style.paddingLeft).toBe(defaultTheme.space['4']); expect(box.props.style.paddingRight).toBe(defaultTheme.space['4']); expect(box.props.style.paddingTop).toBe(defaultTheme.space['4']); expect(box.props.style.paddingBottom).toBe(defaultTheme.space['4']); const box2 = getByTestId('test2'); expect(box2.props.style.paddingLeft).toBe(defaultTheme.space['5']); expect(box2.props.style.paddingRight).toBe(defaultTheme.space['5']); expect(box2.props.style.paddingTop).toBe(defaultTheme.space['5']); expect(box2.props.style.paddingBottom).toBe(defaultTheme.space['5']); }); it('resolves platform props', () => { Platform.OS = 'android'; const { getByTestId } = render( <Provider> <Box p={5} _android={{ p: 10 }} testID="test"> hello world </Box> </Provider> ); const box = getByTestId('test'); expect(box.props.style.paddingLeft).toBe(defaultTheme.space['10']); expect(box.props.style.paddingRight).toBe(defaultTheme.space['10']); expect(box.props.style.paddingTop).toBe(defaultTheme.space['10']); expect(box.props.style.paddingBottom).toBe(defaultTheme.space['10']); }); it('resolves base style with props', () => { const newTheme = extendTheme({ components: { Box: { baseStyle: { py: 10, bg: 'cyan.500', }, }, }, }); const { getByTestId } = render( <Provider theme={newTheme}> <Box p={5} testID="test"> hello world </Box> </Provider> ); const box = getByTestId('test'); expect(box.props.style).toEqual({ paddingTop: newTheme.space['5'], paddingBottom: newTheme.space['5'], paddingLeft: newTheme.space['5'], paddingRight: newTheme.space['5'], backgroundColor: newTheme.colors.cyan['500'], }); }); it('resolves base style and variants with props', () => { const newTheme = extendTheme({ components: { Box: { baseStyle: { py: 10, bg: 'cyan.500', }, variants: { myBox: () => ({ mt: 10, }), }, }, }, }); const { getByTestId } = render( <Provider theme={newTheme}> <Box p={5} testID="test" //@ts-ignore variant="myBox" > hello world </Box> </Provider> ); const box = getByTestId('test'); expect(box.props.style).toEqual({ marginTop: newTheme.space['10'], paddingTop: newTheme.space['5'], paddingBottom: newTheme.space['5'], paddingLeft: newTheme.space['5'], paddingRight: newTheme.space['5'], backgroundColor: newTheme.colors.cyan['500'], }); }); it('resolves base style, variants and sizes with props', () => { const newTheme = extendTheme({ components: { Box: { baseStyle: { py: 10, bg: 'cyan.500', }, variants: { myBox: () => ({ mt: 10, }), }, sizes: { xs: { height: 10, }, }, }, }, }); const { getByTestId } = render( <Provider theme={newTheme}> <Box p={5} testID="test" //@ts-ignore variant="myBox" //@ts-ignore // size="xs" > hello world </Box> </Provider> ); const box = getByTestId('test'); expect(box.props.style).toEqual({ marginTop: newTheme.space['10'], paddingTop: newTheme.space['5'], paddingBottom: newTheme.space['5'], paddingLeft: newTheme.space['5'], paddingRight: newTheme.space['5'], height: newTheme.sizes['10'], backgroundColor: newTheme.colors.cyan['500'], }); }); it('tests component sizes resolution', () => { const { getByTestId } = render( <Provider> <Image source={{ uri: 'https://nativebase.io/img/nativebase-logo.svg' }} alt="test-image" size="md" testID="image" /> <Spinner size="sm" testID="spinner" /> </Provider> ); const image = getByTestId('image'); const spinner = getByTestId('spinner'); expect(image.props.style).toEqual({ height: defaultTheme.space['20'], maxWidth: '100%', width: defaultTheme.space['20'], }); expect(spinner.props.style).toEqual([[{}, { dataSet: {} }], undefined]); }); it('resolves base style and variants, sizes and default props with props', () => { const newTheme = extendTheme({ components: { Box: { baseStyle: { py: 10, bg: 'cyan.500', }, variants: { myBox: () => ({ mt: 10, }), }, sizes: { xs: { height: 10, }, }, defaultProps: { size: 'xs', }, }, }, }); const { getByTestId } = render( <Provider theme={newTheme}> <Box p={5} testID="test" //@ts-ignore variant="myBox" > hello world </Box> </Provider> ); const box = getByTestId('test'); expect(box.props.style).toEqual({ marginTop: newTheme.space['10'], paddingTop: newTheme.space['5'], paddingBottom: newTheme.space['5'], paddingLeft: newTheme.space['5'], paddingRight: newTheme.space['5'], height: newTheme.sizes['10'], backgroundColor: newTheme.colors.cyan['500'], }); }); it('tests alpha opacity resolution', () => { const { getByTestId } = render( <Provider> <Box p={2} bg="primary.400:alpha.50" testID="test"> hello world </Box> </Provider> ); const box = getByTestId('test'); expect(box.props.style.backgroundColor).toBe( 'rgba(34, 211, 238, ' + defaultTheme.opacity['50'] + ')' ); }); it('resolves negative margins', () => { const { getByTestId } = render( <Provider> <Box m={-5} mt={'-10'} testID="test"> hello world </Box> </Provider> ); const box = getByTestId('test'); expect(box.props.style).toEqual({ marginTop: -defaultTheme.space['10'], marginRight: -defaultTheme.space['5'], marginBottom: -defaultTheme.space['5'], marginLeft: -defaultTheme.space['5'], }); }); it('resolves shadow from theme', () => { const { getByTestId } = render( <Provider> <Box shadow={9} testID="test"> hello world </Box> </Provider> ); const box = getByTestId('test'); expect(box.props.style).toEqual(defaultTheme.shadows[9]); }); it('FormControl: pseudo props test ', () => { const { getByTestId } = render( <Provider> <FormControl isDisabled> <FormControl.HelperText testID="test" _disabled={{ borderLeftWidth: 1, mt: 1, px: 1, pl: 2, borderColor: 'gray.400', }} /> </FormControl> </Provider> ); const formControl = getByTestId('test'); expect(formControl.props.style).toEqual({ borderLeftWidth: 1, marginTop: defaultTheme.space['1'], paddingLeft: defaultTheme.space['2'], paddingRight: defaultTheme.space['1'], borderColor: defaultTheme.colors.gray['400'], }); }); it('Menu: style props test', () => { const { getByTestId } = render( <Provider> <Menu trigger={(triggerProps) => { return ( <Pressable testID="pressableTest" accessibilityLabel="More options menu" {...triggerProps} > Open menu </Pressable> ); }} > <Menu.Item>Arial</Menu.Item> <Menu.Item bg="blue.300" testID="test"> Nunito Sans </Menu.Item> <Menu.Item testID="test1" isDisabled _disabled={{ bg: 'pink.300' }}> Tahoma </Menu.Item> </Menu> </Provider> ); const triggerElement = getByTestId('pressableTest'); fireEvent.press(triggerElement); const menuItem = getByTestId('test'); const disabledMenuItem = getByTestId('test1'); expect(menuItem.props.style.backgroundColor).toBe( defaultTheme.colors.blue['300'] ); expect(disabledMenuItem.props.style.backgroundColor).toBe( defaultTheme.colors.pink['300'] ); }); it('Button: style props test', () => { const { getByTestId } = render( <Provider> <Button testID="test" bg="pink.900" _text={{ color: 'cyan.100', testID: 'test1' }} > PRIMARY </Button> </Provider> ); const buttonElement = getByTestId('test'); const buttonText = getByTestId('test1'); expect(buttonText.props.style.color).toBe(defaultTheme.colors.cyan['100']); expect(buttonElement.props.style.backgroundColor).toBe( defaultTheme.colors.pink['900'] ); }); it('Button: style props test on ios with dark mode', () => { const newTheme = extendTheme({ config: { initialColorMode: 'dark' }, }); Platform.OS = 'ios'; const { getByTestId } = render( <Provider theme={newTheme}> <Button testID="test" _ios={{ _dark: { bg: 'pink.900' } }} _text={{ color: 'cyan.100', testID: 'test1' }} > PRIMARY </Button> </Provider> ); const buttonElement = getByTestId('test'); const buttonText = getByTestId('test1'); expect(buttonText.props.style.color).toBe(defaultTheme.colors.cyan['100']); expect(buttonElement.props.style.backgroundColor).toBe( defaultTheme.colors.pink['900'] ); }); it('Button: style responsive props test on ios with dark mode', () => { const newTheme = extendTheme({ config: { initialColorMode: 'dark' }, }); Platform.OS = 'ios'; const { getByTestId } = render( <Provider theme={newTheme}> <Button testID="test" _ios={{ _dark: { bg: ['pink.900', 'blue.900', 'cyan.900'] } }} _text={{ color: 'cyan.100', testID: 'test1' }} > PRIMARY </Button> </Provider> ); const buttonElement = getByTestId('test'); const buttonText = getByTestId('test1'); expect(buttonText.props.style.color).toBe(defaultTheme.colors.cyan['100']); expect(buttonElement.props.style.backgroundColor).toBe( defaultTheme.colors.blue['900'] ); }); it('Image: style responsive props test on ios with dark mode', () => { const newTheme = extendTheme({ config: { initialColorMode: 'dark' }, }); Platform.OS = 'ios'; const { getByTestId } = render( <Provider theme={newTheme}> <Image testID="test" source={{ uri: 'https://wallpaperaccess.com/full/317501jpg', }} alt="Alternate Text" _ios={{ _dark: { source: { uri: 'https://www.w3schools.com/css/img_lightsjpg', }, size: ['sm', 'md', 'xl'], }, }} /> </Provider> ); const imageElement = getByTestId('test'); expect(imageElement.props.style).toEqual({ height: defaultTheme.space['20'], maxWidth: '100%', width: defaultTheme.space['20'], }); }); it('Input: Basic check', () => { const { getByTestId } = render( <Provider> <Input _stack={{ testID: 'StackTest' }} _input={{ testID: 'test' }} w="100%" mx={3} placeholder="Default Input" placeholderTextColor="blueGray.400" /> </Provider> ); const inputElement = getByTestId('test'); const inputElementStack = getByTestId('StackTest'); expect(inputElement.props.style.width).toBe('100%'); expect(inputElement.props.placeholderTextColor).toBe( defaultTheme.colors.blueGray['400'] ); expect(inputElementStack.props.style.marginLeft).toBe( defaultTheme.space['3'] ); expect(inputElementStack.props.style.marginRight).toBe( defaultTheme.space['3'] ); }); it('Input: color mode', () => { const newTheme = extendTheme({ config: { initialColorMode: 'dark' }, }); const { getByTestId } = render( <Provider theme={newTheme}> <Input _input={{ testID: 'test' }} _light={{ placeholderTextColor: 'blueGray.400', }} _dark={{ placeholderTextColor: 'blueGray.50', }} /> </Provider> ); const inputElement = getByTestId('test'); expect(inputElement.props.placeholderTextColor).toBe( defaultTheme.colors.blueGray['50'] ); }); it('Input: size', () => { const newTheme = extendTheme({ config: { initialColorMode: 'dark' }, }); const { getByTestId } = render( <Provider theme={newTheme}> <Input _input={{ testID: 'test' }} size="sm" variant="outline" _dark={{ size: 'md', }} /> </Provider> ); const inputElement = getByTestId('test'); expect(inputElement.props.style.fontSize).toBe(defaultTheme.fontSizes.sm); }); it('Input: variant', () => { const { getByTestId } = render( <Provider> <Input _stack={{ testID: 'test' }} variant="underlined" /> </Provider> ); const inputElement = getByTestId('test'); expect(inputElement.props.style.borderBottomWidth).toBe(1); }); // it('Input: inputElements', () => { // const { getByTestId } = render( // <Provider> // <Input // testID="test1" // InputLeftElement={<Button testID="test2">leftIcon</Button>} // placeholder="Input" // /> // </Provider> // ); // const inputElement = getByTestId('test1'); // const iconElement = getByTestId('test2'); // console.log(inputElement, '!!!!!'); // console.log('==========='); // console.log(inputElement.props, '!!!!!'); // expect(inputElement.props.InputLeftElement).toBe(iconElement); // }); it('Input: style props test on ios with dark mode', () => { const newTheme = extendTheme({ config: { initialColorMode: 'dark' }, }); Platform.OS = 'ios'; const { getByTestId } = render( <Provider theme={newTheme}> <Input _stack={{ testID: 'stackTest' }} _input={{ testID: 'test' }} _ios={{ _dark: { variant: 'underlined', size: 'sm' } }} variant="outline" size="lg" /> </Provider> ); const inputElement = getByTestId('test'); const inputElementStack = getByTestId('stackTest'); expect(inputElementStack.props.style.borderBottomWidth).toBe(1); // as input of 'sm' size is mapped to 'xs' fontsize expect(inputElement.props.style.fontSize).toBe(defaultTheme.fontSizes.xs); }); // it('Input: inputElemets', () => { // const { getByTestId } = render( // <Provider> // <Input // testID="test1" // InputLeftElement={<Button testID="test2">leftIcon</Button>} // placeholder="Input" // /> // </Provider> // ); // const inputElement = getByTestId('test1'); // const iconElement = getByTestId('test2'); // console.log(inputElement, '!!!!!'); // console.log('==========='); // console.log(inputElement.props, '!!!!!'); // expect(inputElement.props.InputLeftElement).toBe(iconElement); // }); it('Input: disabled', () => { const { getByTestId } = render( <Provider> <Input _input={{ testID: 'test' }} type="password" isDisabled={true} isRequired={true} /> </Provider> ); const inputElement = getByTestId('test'); expect(inputElement.props.disabled).toBe(true); expect(inputElement.props.required).toBe(true); }); // ========================================== it('handles defaults and onChange on checkBoxGroup', () => { const { getAllByRole } = render( <Provider initialWindowMetrics={{ frame: { x: 0, y: 0, width: 0, height: 0 }, insets: { top: 0, left: 0, right: 0, bottom: 0 }, }} > <CheckBoxGroup /> </Provider> ); const checkbox = getAllByRole('checkbox'); expect(checkbox.length).toBe(4); expect(checkbox[0].props.accessibilityState.checked).toBe(true); expect(checkbox[1].props.accessibilityState.checked).toBe(false); expect(checkbox[2].props.accessibilityState.checked).toBe(true); expect(checkbox[3].props.accessibilityState.checked).toBe(false); fireEvent.press(checkbox[1]); expect(checkbox[1].props.accessibilityState.checked).toBe(true); }); it('checkBox: disabled, checked', () => { const { getAllByRole } = render( <Provider initialWindowMetrics={{ frame: { x: 0, y: 0, width: 0, height: 0 }, insets: { top: 0, left: 0, right: 0, bottom: 0 }, }} > <Checkbox value="Item 1 "> <Text mx={2}>Item 1</Text> </Checkbox> <Checkbox value="Item 2 " isDisabled> <Text mx={2}>Item 2</Text> </Checkbox> <Checkbox value="Item 3" isChecked> <Text mx={2}>Item 3</Text> </Checkbox> <Checkbox colorScheme="orange" value="Indeterminate Item" isInvalid> <Text mx={2}>Indeterminate Item</Text> </Checkbox> </Provider> ); const checkbox = getAllByRole('checkbox'); expect(checkbox.length).toBe(4); expect(checkbox[1].props.accessibilityState.disabled).toBe(true); expect(checkbox[2].props.accessibilityState.checked).toBe(true); // expect(checkbox[3].props.accessibilityState.invalid).toBe(true); }); // it('Checkbox: style props test with dark mode', () => { // const newTheme = extendTheme({ // config: { initialColorMode: 'dark' }, // }); // const { getAllByRole } = render( // <Provider theme={newTheme}> // <Checkbox // value="Item 1" // isChecked={true} // isDisabled={false} // _dark={{ // isChecked: false, // isDisabled: true, // }} // > // <Text mx={2}>Item 1</Text> // </Checkbox> // </Provider> // ); // let checkbox = getAllByRole('checkbox'); // console.log(checkbox[0].props.accessibilityState, '@@@@'); // expect(checkbox[0].props.accessibilityState.checked).toBe(false); // expect(checkbox[0].props.accessibilityState.disabled).toBe(true); // }); // it('Checkbox: style props test on ios with dark mode', () => { // const newTheme = extendTheme({ // config: { initialColorMode: 'dark' }, // }); // Platform.OS = 'ios'; // const { getAllByRole } = render( // <Provider theme={newTheme}> // <Checkbox // value="Item 1" // isChecked={true} // isDisabled={false} // _ios={{ // _dark: { // isChecked: false, // isDisabled: true, // }, // }} // > // <Text mx={2}>Item 1</Text> // </Checkbox> // </Provider> // ); // let checkbox = getAllByRole('checkbox'); // console.log(checkbox[0].props.accessibilityState, '@@@@'); // expect(checkbox[0].props.accessibilityState.checked).toBe(false); // expect(checkbox[0].props.accessibilityState.disabled).toBe(true); // }); it('onChange on checkBox', () => { const { getAllByRole } = render( <Provider initialWindowMetrics={{ frame: { x: 0, y: 0, width: 0, height: 0 }, insets: { top: 0, left: 0, right: 0, bottom: 0 }, }} > <Checkbox value="item 1" /> </Provider> ); const checkbox = getAllByRole('checkbox'); expect(checkbox.length).toBe(1); fireEvent.press(checkbox[0]); expect(checkbox[0].props.accessibilityState.checked).toBe(true); }); // it('CustomIcon checkBox', () => { // let { getAllByRole, getByTestId } = render( // <Provider> // <Checkbox // value="orange" // colorScheme="orange" // size="md" // icon={<Icon testID="icon" as={<InfoIcon />} />} // defaultIsChecked // > // Info // </Checkbox> // </Provider> // ); // let checkbox = getAllByRole('checkbox'); // let nestedIcon = getByTestId('icon'); // expect(checkbox[0].props.icon).toBe(nestedIcon); // }); // ========================================== it('Slider: basic', () => { const { getByTestId } = render( <Provider> <Slider testID="slider" // Need to test // defaultValue={70} minValue={0} maxValue={100} accessibilityLabel="hello world" step={10} colorScheme="red" size="sm" > <Slider.Track> <Slider.FilledTrack /> </Slider.Track> <Slider.Thumb /> </Slider> </Provider> ); const sliderElement = getByTestId('slider'); expect(sliderElement.props.minValue).toBe(0); expect(sliderElement.props.maxValue).toBe(100); expect(sliderElement.props.step).toBe(10); expect(sliderElement.props.thumbSize).toBe(4); expect(sliderElement.props.sliderSize).toBe(4); expect(sliderElement.props.colorScheme).toBe('red'); }); // ========================================== // it('Modal: size', () => { // const { getByTestId } = render( // <Provider> // <Modal isOpen={true} size="sm"> // <Modal.Content testID="size"> // <Modal.Header>Modal Title</Modal.Header> // <Modal.Body> // Sit nulla est ex deserunt exercitation anim occaecat. Nostrud // ullamco deserunt aute id consequat veniam incididunt duis in sint // irure nisi. Mollit officia cillum Lorem ullamco minim nostrud elit // officia tempor esse quis. Sunt ad dolore quis aute consequat. // Magna exercitation reprehenderit magna aute tempor cupidatat // consequat elit dolor adipisicing. Mollit dolor eiusmod sunt ex // incididunt cillum quis. Velit duis sit officia eiusmod Lorem // aliqua enim laboris do dolor eiusmod. Et mollit incididunt nisi // consectetur esse laborum eiusmod pariatur // </Modal.Body> // </Modal.Content> // </Modal> // </Provider> // ); // const modalElement = getByTestId('size'); // // console.log(modalElement, 'jdj'); // expect(modalElement.props.style.width).toBe('60%'); // }); it('Slider: style props test with dark mode', () => { const newTheme = extendTheme({ config: { initialColorMode: 'dark' }, }); const { getByTestId } = render( <Provider theme={newTheme}> <Slider testID="test" _dark={{ minValue: 20, maxValue: 120, step: 25, colorScheme: 'blue', size: 'md', }} minValue={0} maxValue={100} accessibilityLabel="hello world" step={10} colorScheme="red" size="sm" > <Slider.Track> <Slider.FilledTrack /> </Slider.Track> <Slider.Thumb /> </Slider> </Provider> ); const sliderElement = getByTestId('test'); expect(sliderElement.props.minValue).toBe(20); expect(sliderElement.props.maxValue).toBe(120); expect(sliderElement.props.step).toBe(25); expect(sliderElement.props.thumbSize).toBe(5); expect(sliderElement.props.sliderSize).toBe(5); expect(sliderElement.props.colorScheme).toBe('blue'); }); it('tests lineHeight & letterspacing in text ', () => { const { getByTestId } = render( <Provider> <Text /* @ts-ignore */ fontSize="20px" lineHeight="5xl" letterSpacing="xl" testID="test" > This is a text </Text> </Provider> ); const text = getByTestId('test'); expect(text.props.style.lineHeight).toBe(80); expect(text.props.style.letterSpacing).toBe(1); }); it('Slider: style props test on ios with dark mode', () => { const newTheme = extendTheme({ config: { initialColorMode: 'dark' }, }); Platform.OS = 'ios'; const { getByTestId } = render( <Provider theme={newTheme}> <Slider testID="test" _ios={{ _dark: { minValue: 10, maxValue: 110, step: 15, colorScheme: 'green', size: 'md', }, }} minValue={0} maxValue={100} accessibilityLabel="hello world" step={10} colorScheme="red" size="sm" > <Slider.Track> <Slider.FilledTrack /> </Slider.Track> <Slider.Thumb /> </Slider> </Provider> ); const sliderElement = getByTestId('test'); expect(sliderElement.props.minValue).toBe(10); expect(sliderElement.props.maxValue).toBe(110); expect(sliderElement.props.step).toBe(15); expect(sliderElement.props.thumbSize).toBe(5); expect(sliderElement.props.sliderSize).toBe(5); expect(sliderElement.props.colorScheme).toBe('green'); }); it('HStack: basic', () => { const { getByTestId } = render( <Provider> <HStack testID="hstack"> <Box>1</Box> <Box>2</Box> <Box>3</Box> </HStack> </Provider> ); const hstackElement = getByTestId('hstack'); expect(hstackElement.props.style.flexDirection).toBe('row'); }); it('HStack: direction', () => { const { getByTestId } = render( <Provider> <HStack testID="test" direction="column"> <Box>1</Box> <Box>2</Box> <Box>3</Box> </HStack> </Provider> ); const hstackElement = getByTestId('test'); expect(hstackElement.props.style.flexDirection).toBe('column'); }); // it('Icon: basic', () => { // const { getByTestId } = render( // <Provider> // <Icon as={<Ionicons name="md-checkmark-circle" />} /> // </Provider> // ); // const iconElement = getByTestId('test123'); // expect(iconElement.props.style.backgroundColor).toBe( // defaultTheme.colors.red['200'] // ); // }); // it('Icon: Nativebase icons', () => { // const { getByTestId } = render( // <Provider> // <MoonIcon testId="test" /> // </Provider> // ); // const iconElement = getByTestId('test'); // expect(pressableElement.props.style.backgroundColor).toBe( // defaultTheme.colors.red['200'] // ); // }); it('Pressable: style props test', () => { const { getByTestId } = render( <Provider> <Pressable testID="test" bg="red.200" _hover={{ bg: 'teal.300' }}> <Text>hello world</Text> </Pressable> </Provider> ); const pressableElement = getByTestId('test'); expect(pressableElement.props.style.backgroundColor).toBe( defaultTheme.colors.red['200'] ); }); // it('Pressable: style props test on ios with dark mode', () => { // const newTheme = extendTheme({ // config: { initialColorMode: 'dark' }, // }); // Platform.OS = 'ios'; // const { getByTestId } = render( // <Provider theme={newTheme}> // <Pressable testID="test" _ios={{ _dark: { bg: 'pink.900' } }}> // PRIMARY // </Pressable> // </Provider> // ); // const buttonElement = getByTestId('test'); // expect(buttonElement.props.style.backgroundColor).toBe( // defaultTheme.colors.pink['900'] // ); // }); // it('Pressable: style responsive props test on ios with dark mode', () => { // const newTheme = extendTheme({ // config: { initialColorMode: 'dark' }, // }); // Platform.OS = 'ios'; // const { getByTestId } = render( // <Provider theme={newTheme}> // <Pressable // testID="test" // _ios={{ _dark: { bg: ['pink.900', 'blue.900', 'cyan.900'] } }} // > // PRIMARY // </Pressable> // </Provider> // ); // const buttonElement = getByTestId('test'); // expect(buttonElement.props.style.backgroundColor).toBe( // defaultTheme.colors.blue['900'] // ); // }); // }); it('HStack: style props test with dark mode', () => { const newTheme = extendTheme({ config: { initialColorMode: 'dark' }, }); const { getByTestId } = render( <Provider theme={newTheme}> <HStack testID="test" direction="column" _dark={{ direction: 'row', }} > <Box>1</Box> <Box>2</Box> <Box>3</Box> </HStack> </Provider> ); const hstackElement = getByTestId('test'); expect(hstackElement.props.style.flexDirection).toBe('row'); }); it('HStack: style props test on ios & dark mode', () => { const newTheme = extendTheme({ config: { initialColorMode: 'dark' }, }); const { getByTestId } = render( <Provider theme={newTheme}> <Box> <Text // @ts-ignore fontSize="12px" testID="test" lineHeight="4xl" letterSpacing="xl" _ios={{ _dark: { fontSize: '15px', letterSpacing: 'lg', lineHeight: '3xl', }, }} > This is a text </Text> <Text testID="responsiveLineHeight" lineHeight="3xl" fontSize={['12px', '13px']} > hello world </Text> </Box> </Provider> ); const text = getByTestId('test'); const responsiveLineHeight = getByTestId('responsiveLineHeight'); expect(text.props.style.lineHeight).toBe(37.5); expect(text.props.style.letterSpacing).toBe(0.375); expect(responsiveLineHeight.props.style.lineHeight).toBe(32.5); }); it('Heading: style props test on ios with dark mode', () => { const newTheme = extendTheme({ config: { initialColorMode: 'dark' }, }); Platform.OS = 'ios'; const { getByTestId } = render( <Provider theme={newTheme}> <Box> <Heading // @ts-ignore fontSize="12px" testID="test" lineHeight="4xl" letterSpacing="xl" _ios={{ _dark: { fontSize: '15px', letterSpacing: 'lg', lineHeight: '3xl', }, }} > This is a Heading </Heading> </Box> </Provider> ); const heading = getByTestId('test'); expect(heading.props.style.lineHeight).toBe(37.5); expect(heading.props.style.letterSpacing).toBe(0.375); }); it('Pseudo props test: importatnt on Button', () => { const newTheme = extendTheme({ config: { initialColorMode: 'dark' }, components: { Button: { baseStyle: { _important: { bg: 'green.400', }, }, }, }, }); const { getByTestId } = render( <Provider theme={newTheme}> <Button bg="amber.500" testID="test"> Button </Button> </Provider> ); const button = getByTestId('test'); expect(button.props.style.backgroundColor).toBe( defaultTheme.colors.green['400'] ); }); it('Pseudo props test: normal prop on light and dark', () => { const newTheme = extendTheme({ config: { initialColorMode: 'dark' }, components: { Button: { baseStyle: { _light: { bg: 'green.700', }, _dark: { bg: 'green.100', }, }, }, }, }); const { getByTestId } = render( <Provider theme={newTheme}> <Button bg="amber.500" testID="test"> Button </Button> </Provider> ); const button = getByTestId('test'); expect(button.props.style.backgroundColor).toBe( defaultTheme.colors.amber['500'] ); }); it('Pseudo props test: _important overrided', () => { const newTheme = extendTheme({ config: { initialColorMode: 'dark' }, components: { Button: { baseStyle: { _important: { bg: 'green.400', }, }, variants: { solid: { _important: { bg: 'emerald.800', _text: { color: 'white', }, }, }, }, }, }, }); const { getByTestId } = render( <Provider theme={newTheme}> <Button bg="amber.500" testID="test"> Button </Button> </Provider> ); const button = getByTestId('test'); expect(button.props.style.backgroundColor).toBe( defaultTheme.colors.emerald['800'] ); }); }); // ========================================================= // it('Modal: size', () => { // const { getByTestId } = render( // <Provider> // <Modal isOpen={true} size="sm"> // <Modal.Content testID="size"> // <Modal.Header>Modal Title</Modal.Header> // <Modal.Body> // Sit nulla est ex deserunt exercitation anim occaecat. Nostrud // ullamco deserunt aute id consequat veniam incididunt duis in sint // irure nisi. Mollit officia cillum Lorem ullamco minim nostrud elit // officia tempor esse quis. Sunt ad dolore quis aute consequat. // Magna exercitation reprehenderit magna aute tempor cupidatat // consequat elit dolor adipisicing. Mollit dolor eiusmod sunt ex // incididunt cillum quis. Velit duis sit officia eiusmod Lorem // aliqua enim laboris do dolor eiusmod. Et mollit incididunt nisi // consectetur esse laborum eiusmod pariatur // </Modal.Body> // </Modal.Content> // </Modal> // </Provider> // ); // const modalElement = getByTestId('size'); // expect(modalElement.props.style.width).toBe('60%'); // });
4,756
0
petrpan-code/GeekyAnts/NativeBase/src/theme
petrpan-code/GeekyAnts/NativeBase/src/theme/tests/findLastValidBreakpoint.test.tsx
import { findLastValidBreakpoint } from './../../theme/tools/utils'; import { theme } from '../../theme'; describe('mode', () => { // const theme = useTheme(); test('First array value', () => { expect(findLastValidBreakpoint([1, 2], theme.breakpoints, 0)).toBe(1); }); test('Middle array value', () => { expect(findLastValidBreakpoint([1, 2, 3], theme.breakpoints, 1)).toBe(2); }); test('Last array value', () => { expect(findLastValidBreakpoint([1, 2, 3], theme.breakpoints, 2)).toBe(3); }); test('First Object value', () => { expect( findLastValidBreakpoint({ base: 1, sm: 2, lg: 3 }, theme.breakpoints, 0) ).toBe(1); }); test('Middle object value 1', () => { expect( findLastValidBreakpoint({ base: 1, sm: 2, lg: 3 }, theme.breakpoints, 1) ).toBe(2); }); test('Middle object value 2', () => { expect( findLastValidBreakpoint({ base: 1, sm: 2, lg: 3 }, theme.breakpoints, 2) ).toBe(2); }); test('Last object value', () => { expect( findLastValidBreakpoint({ base: 1, sm: 2, lg: 3 }, theme.breakpoints, 3) ).toBe(3); }); });
4,757
0
petrpan-code/GeekyAnts/NativeBase/src/theme
petrpan-code/GeekyAnts/NativeBase/src/theme/tests/getClosestBreakpoint.test.tsx
import { getClosestBreakpoint } from './../../theme/tools/utils'; const defaultBreakpoints = { base: 0, sm: 480, md: 768, lg: 992, xl: 1280, }; describe('mode', () => { test('Base value', () => { expect(getClosestBreakpoint(defaultBreakpoints, 0)).toBe(0); }); test('Base-Sm value', () => { expect(getClosestBreakpoint(defaultBreakpoints, 10)).toBe(0); }); test('Sm value', () => { expect(getClosestBreakpoint(defaultBreakpoints, 480)).toBe(1); }); test('Sm-md value', () => { expect(getClosestBreakpoint(defaultBreakpoints, 500)).toBe(1); }); test('Lg value', () => { expect(getClosestBreakpoint(defaultBreakpoints, 1000)).toBe(3); }); });
4,758
0
petrpan-code/GeekyAnts/NativeBase/src/theme
petrpan-code/GeekyAnts/NativeBase/src/theme/tests/hasValidBreakpointFormat.test.tsx
import { hasValidBreakpointFormat } from './../../theme/tools/utils'; import { theme as defaultTheme } from '../../theme'; describe('mode', () => { test('Empty array', () => { expect(hasValidBreakpointFormat([], defaultTheme.breakpoints)).toBe(false); }); test('Array', () => { expect(hasValidBreakpointFormat([1, 2], defaultTheme.breakpoints)).toBe( true ); }); test('Valid Object', () => { expect( hasValidBreakpointFormat({ base: 1, sm: 2 }, defaultTheme.breakpoints) ).toBe(true); }); test('Invalid Object', () => { expect( hasValidBreakpointFormat( { base: 1, sm: 2, ab: 1 }, defaultTheme.breakpoints ) ).toBe(false); }); });
4,759
0
petrpan-code/GeekyAnts/NativeBase/src/theme
petrpan-code/GeekyAnts/NativeBase/src/theme/tests/mode.test.tsx
import { mode } from './../../theme/tools/colors'; describe('mode', () => { test('default', () => { expect(mode('light', 'dark')({})).toBe('light'); }); test('light', () => { expect(mode('light', 'dark')({ colorMode: 'light' })).toBe('light'); }); test('dark', () => { expect(mode('light', 'dark')({ colorMode: 'dark' })).toBe('dark'); }); });
4,887
0
petrpan-code/GeekyAnts/NativeBase/src/utils
petrpan-code/GeekyAnts/NativeBase/src/utils/tests/filterShadow.test.tsx
import { filterShadowProps } from './../../utils/filterShadowProps'; describe('filterShadowProps', () => { test('empty', () => { expect(filterShadowProps({}, {}, 'web')).toEqual({ style: {} }); }); test('basic', () => { expect( filterShadowProps( { top: 10, shadowColor: '#FFF', shadowOffset: { width: 0, height: 1, }, shadowOpacity: 0.18, shadowRadius: 1.0, }, {}, 'web' ) ).toEqual({ top: 10, style: { shadowColor: '#FFF', shadowOffset: { width: 0, height: 1, }, shadowOpacity: 0.18, shadowRadius: 1.0, }, }); }); });
7,122
0
petrpan-code/airbnb/visx/packages/visx-annotation
petrpan-code/airbnb/visx/packages/visx-annotation/test/Annotation.test.tsx
import { render } from '@testing-library/react'; import React, { useContext } from 'react'; import { Annotation } from '../src'; import AnnotationContext from '../src/context/AnnotationContext'; describe('<Annotation />', () => { it('should be defined', () => { expect(Annotation).toBeDefined(); }); it('should provide AnnotationContext', () => { expect.assertions(1); const annotation = { x: -50, y: 100, dx: 1000, dy: 7 }; function AnnotationChild() { const annotationContext = useContext(AnnotationContext); expect(annotationContext).toEqual(annotation); return null; } render( <Annotation {...annotation}> <AnnotationChild /> </Annotation>, ); }); });
7,123
0
petrpan-code/airbnb/visx/packages/visx-annotation
petrpan-code/airbnb/visx/packages/visx-annotation/test/CircleSubject.test.tsx
import React from 'react'; import { shallow } from 'enzyme'; import { CircleSubject } from '../src'; describe('<CircleSubject />', () => { it('should be defined', () => { expect(CircleSubject).toBeDefined(); }); it('should render a cirlce', () => { expect(shallow(<CircleSubject />).find('circle')).toHaveLength(1); }); });
7,124
0
petrpan-code/airbnb/visx/packages/visx-annotation
petrpan-code/airbnb/visx/packages/visx-annotation/test/Connector.test.tsx
import React from 'react'; import { shallow } from 'enzyme'; import { Connector } from '../src'; describe('<Connector />', () => { it('should be defined', () => { expect(Connector).toBeDefined(); }); it('should render a path', () => { expect(shallow(<Connector />).find('path')).toHaveLength(1); }); });
7,125
0
petrpan-code/airbnb/visx/packages/visx-annotation
petrpan-code/airbnb/visx/packages/visx-annotation/test/EditableAnnotation.test.tsx
import React from 'react'; import { shallow } from 'enzyme'; import { Annotation, EditableAnnotation } from '../src'; import { EditableAnnotationProps } from '../lib/components/EditableAnnotation'; describe('<EditableAnnotation />', () => { function setup(props?: Partial<EditableAnnotationProps>) { return shallow( <EditableAnnotation width={100} height={100} {...props}> <div /> </EditableAnnotation>, ); } it('should be defined', () => { expect(EditableAnnotation).toBeDefined(); }); it('should render two resize handles', () => { expect(setup().find('circle')).toHaveLength(2); }); it('should render one resize handle if canEditLabel or canEditSubject are false', () => { expect(setup({ canEditLabel: false }).find('circle')).toHaveLength(1); expect(setup({ canEditSubject: false }).find('circle')).toHaveLength(1); }); it('should render an Annotation', () => { expect(setup().find(Annotation)).toHaveLength(1); }); });
7,126
0
petrpan-code/airbnb/visx/packages/visx-annotation
petrpan-code/airbnb/visx/packages/visx-annotation/test/HtmlLabel.test.tsx
import React from 'react'; import { ResizeObserver } from '@juggle/resize-observer'; import { render } from '@testing-library/react'; import { HtmlLabel } from '../src'; describe('<HtmlLabel />', () => { it('should render HTML content', () => { const { container } = render( <svg> <HtmlLabel resizeObserverPolyfill={ResizeObserver}> <h1>Hello, HTML</h1> </HtmlLabel> </svg>, ); const h1Element = container.querySelector('h1'); expect(h1Element).not.toBeNull(); }); });
7,127
0
petrpan-code/airbnb/visx/packages/visx-annotation
petrpan-code/airbnb/visx/packages/visx-annotation/test/Label.test.tsx
import React from 'react'; import { ResizeObserver } from '@juggle/resize-observer'; import Text from '@visx/text/lib/Text'; import { shallow } from 'enzyme'; import { Label } from '../src'; describe('<Label />', () => { it('should be defined', () => { expect(Label).toBeDefined(); }); it('should render title Text', () => { expect( shallow(<Label title="title test" resizeObserverPolyfill={ResizeObserver} />) .dive() .children() .find(Text) .prop('children'), ).toBe('title test'); }); it('should render subtitle Text', () => { expect( shallow( <Label title="title test" subtitle="subtitle test" resizeObserverPolyfill={ResizeObserver} />, ) .dive() .children() .find(Text) .at(1) .prop('children'), ).toBe('subtitle test'); }); it('should render a background', () => { expect( shallow(<Label title="title test" showBackground resizeObserverPolyfill={ResizeObserver} />) .dive() .find('rect'), ).toHaveLength(1); }); it('should render an anchor line', () => { expect( shallow(<Label title="title test" showAnchorLine resizeObserverPolyfill={ResizeObserver} />) .dive() .find('AnchorLine') .dive() .find('line'), ).toHaveLength(1); }); });
7,128
0
petrpan-code/airbnb/visx/packages/visx-annotation
petrpan-code/airbnb/visx/packages/visx-annotation/test/LineSubject.test.tsx
import React from 'react'; import { shallow } from 'enzyme'; import { LineSubject } from '../src'; describe('<LineSubject />', () => { it('should be defined', () => { expect(LineSubject).toBeDefined(); }); it('should render a line', () => { expect(shallow(<LineSubject min={0} max={100} />).find('line')).toHaveLength(1); }); });