Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/storybook/src/plugins/mock-router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ export function mockRouter(): PluginOption {
if (id.includes('src')) {
code = code.replace(
"'@cedarjs/router'",
// TODO(storybook): Use the mock router from @cedarjs/testing instead
"'storybook-framework-cedarjs/dist/mocks/MockRouter'",
)
}
Expand Down
37 changes: 35 additions & 2 deletions packages/testing/build.mts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import fs from 'node:fs'

import { buildCjs, buildEsm } from '@cedarjs/framework-tools'
import { build, buildEsm, defaultBuildOptions } from '@cedarjs/framework-tools'
import {
generateTypesCjs,
generateTypesEsm,
Expand All @@ -10,7 +10,21 @@ import {
await buildEsm()
await generateTypesEsm()

await buildCjs()
await build({
buildOptions: {
...defaultBuildOptions,
tsconfig: 'tsconfig.cjs.json',
outdir: 'dist/cjs',
logOverride: {
// This feels a bit dangerous, I wish I could do this with a comment
// inside the file where I need this for greater control, but I haven't
// found a way to do that yet.
// This is to silence the CJS warning for `import.meta.glob` and
// `import.meta.dirname`
'empty-import-meta': 'silent',
},
},
})
await generateTypesCjs()
await insertCommonJsPackageJson({
buildFileUrl: import.meta.url,
Expand Down Expand Up @@ -71,3 +85,22 @@ fs.writeFileSync(
configJestWebJestSetupPath,
webJestSetupFile.replaceAll('await import', 'require'),
)

// ./src/web/globRoutesImporter.ts contains `import.meta.glob`. This is not
// supported in CJS. And for CJS we don't really use this, but it does get
// imported and executed, so we need to mock it. esbuild will just make
// `import.meta` be an empty object, but that's not quite enough for what we
// need here, so I extend it a bit more.
const globRoutesImporterBuildPath = './dist/cjs/web/globRoutesImporter.js'
const globRoutesImporterFile = fs.readFileSync(
globRoutesImporterBuildPath,
'utf-8',
)

fs.writeFileSync(
globRoutesImporterBuildPath,
globRoutesImporterFile.replaceAll(
'const import_meta = {};',
'const import_meta = { glob: () => ({ "routes.tsx": () => null }) };',
),
)
18 changes: 18 additions & 0 deletions packages/testing/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,10 @@
"default": "./dist/cjs/api/index.js"
}
},
"./api/vitest": {
"types": "./dist/api/vitest/index.d.ts",
"default": "./dist/api/vitest/index.js"
},
"./cache": {
"import": {
"types": "./dist/cache/index.d.ts",
Expand All @@ -82,6 +86,20 @@
"types": "./dist/cjs/web/index.d.ts",
"default": "./dist/cjs/web/index.js"
}
},
"./web/MockRouter.js": {
"import": {
"types": "./dist/web/MockRouter.d.ts",
"default": "./dist/web/MockRouter.js"
},
"require": {
"types": "./dist/cjs/web/MockRouter.d.ts",
"default": "./dist/cjs/web/MockRouter.js"
}
},
"./web/vitest": {
"types": "./dist/web/vitest/index.d.ts",
"default": "./dist/web/vitest/index.js"
}
},
"files": [
Expand Down
46 changes: 46 additions & 0 deletions packages/testing/src/api/mockContext.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
// TODO: See if we can use `GlobalContext` instead of `any` here to more
// closely match the production context.
// https://github.com/cedarjs/cedar/pull/355#discussion_r2264851576
const mockContextStore = new Map<string, any>()
const mockContext = new Proxy(
{},
{
get: (_target, prop) => {
// Handle toJSON() calls, i.e. JSON.stringify(context)
if (prop === 'toJSON') {
return () => mockContextStore.get('context')
}

const ctx = mockContextStore.get('context')

if (!ctx) {
return undefined
}

return ctx[prop]
},
set: (_target, prop, value) => {
const ctx = mockContextStore.get('context')

if (!ctx) {
return false
}

ctx[prop] = value

return true
},
},
)

// eslint-disable-next-line @typescript-eslint/no-empty-object-type
export interface GlobalContext extends Record<string, unknown> {}

export const context = mockContext

export const setContext = (newContext: GlobalContext): GlobalContext => {
mockContextStore.set('context', newContext)
// TODO: See if this should be `newContext` instead
// https://github.com/cedarjs/cedar/pull/355#discussion_r2264851567
return mockContext
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

logic: Returning mockContext instead of newContext creates inconsistency with production behavior where setContext returns the new context proxy

}
59 changes: 59 additions & 0 deletions packages/testing/src/api/vitest/CedarApiVitestEnv.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import { getSchema } from '@prisma/internals'
import 'dotenv-defaults/config.js'
import execa from 'execa'
import type { Environment } from 'vitest/environments'

import { getPaths } from '@cedarjs/project-config'

import { getDefaultDb, checkAndReplaceDirectUrl } from '../directUrlHelpers.js'

const CedarApiVitestEnvironment: Environment = {
name: 'cedar-api',
transformMode: 'ssr',

async setup() {
if (process.env.SKIP_DB_PUSH === '1') {
return {
teardown() {},
}
}

const cedarPaths = getPaths()
const defaultDb = getDefaultDb(cedarPaths.base)

process.env.DATABASE_URL = process.env.TEST_DATABASE_URL || defaultDb

// NOTE: This is a workaround to get the directUrl from the schema
// Instead of using the schema, we can use the config file
// const prismaConfig = await getConfig(rwjsPaths.api.dbSchema)
// and then check for the prismaConfig.datasources[0].directUrl
const prismaSchema = (await getSchema(cedarPaths.api.dbSchema)).toString()

const directUrlEnvVar = checkAndReplaceDirectUrl(prismaSchema, defaultDb)

const command =
process.env.TEST_DATABASE_STRATEGY === 'reset'
? ['prisma', 'migrate', 'reset', '--force', '--skip-seed']
: ['prisma', 'db', 'push', '--force-reset', '--accept-data-loss']

const directUrlDefinition = directUrlEnvVar
? { [directUrlEnvVar]: process.env[directUrlEnvVar] }
: {}

execa.sync(`yarn rw`, command, {
cwd: cedarPaths.api.base,
stdio: 'inherit',
shell: true,
env: {
DATABASE_URL: process.env.DATABASE_URL,
...directUrlDefinition,
},
})

return {
teardown() {},
}
},
}

export default CedarApiVitestEnvironment
3 changes: 3 additions & 0 deletions packages/testing/src/api/vitest/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export { autoImportsPlugin } from './vite-plugin-auto-import.js'
export { cedarVitestApiConfigPlugin } from './vite-plugin-cedar-vitest-api-config.js'
export { trackDbImportsPlugin } from './vite-plugin-track-db-imports.js'
36 changes: 36 additions & 0 deletions packages/testing/src/api/vitest/vite-plugin-auto-import.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import autoImport from 'unplugin-auto-import/vite'

export function autoImportsPlugin() {
return autoImport({
// targets to transform
include: [
/\.[tj]sx?$/, // .ts, .tsx, .js, .jsx
],

// global imports to register
imports: [
// import { mockContext, mockHttpEvent, mockSignedWebhook } from '@cedarjs/testing/api';
{
'@cedarjs/testing/api': [
'mockContext',
'mockHttpEvent',
'mockSignedWebhook',
],
},
// import { gql } from 'graphql-tag'
{
'graphql-tag': ['gql'],
},
// import { context } from '@cedarjs/context'
{
'@cedarjs/context': ['context'],
},
],

// We provide our mocking types elsewhere and so don't need this plugin to
// generate them.
// TODO: Maybe we should have it at least generate the types for the gql
// import? (Or do we already provide that some other way?)
dts: false,
})
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import path from 'node:path'

import type { Plugin } from 'vite'

import { getEnvVarDefinitions, getPaths } from '@cedarjs/project-config'

export function cedarVitestApiConfigPlugin(): Plugin {
return {
name: 'cedar-vitest-plugin',
config: () => {
return {
define: getEnvVarDefinitions(),
ssr: {
noExternal: ['@cedarjs/testing'],
},
resolve: {
alias: {
src: getPaths().api.src,
},
},
test: {
environment: path.join(import.meta.dirname, 'CedarApiVitestEnv.js'),
// fileParallelism: false,
// fileParallelism doesn't work with vitest projects (which is what
// we're using in the root vitest.config.ts). As a workaround we set
// poolOptions instead, which also shouldn't work, but was suggested
// by Vitest team member AriPerkkio (Hiroshi's answer didn't work).
// https://github.com/vitest-dev/vitest/discussions/7416
poolOptions: { forks: { singleFork: true } },
setupFiles: [path.join(import.meta.dirname, 'vitest-api.setup.js')],
},
}
},
}
}
33 changes: 33 additions & 0 deletions packages/testing/src/api/vitest/vite-plugin-track-db-imports.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import type { Plugin } from 'vite'

export function trackDbImportsPlugin(): Plugin {
return {
name: 'db-import-tracker',
transform(code, id) {
// This regex and code content check could potentially match other files.
// It's very unlikely, but it is possible. For now this is good enough
if (
id.match(/\/api\/src\/lib\/db\.(js|ts)$/) &&
code.includes('PrismaClient')
) {
// Inserting the code last (instead of at the top) works nicer with
// sourcemaps
return (
code +
`
;if (typeof globalThis !== "undefined") {
globalThis.__cedarjs_db_imported__ = true;
} else {
throw new Error(
"vite-plugin-track-db-imports: globalThis is undefined. " +
"This is an error with CedarJS"
);
}
`
)
}

return code
},
}
}
Loading
Loading