Skip to content

refactor: use vi.stubEnv instead of process.env#205

Merged
yamcodes merged 6 commits intomainfrom
stub-envs
Oct 7, 2025
Merged

refactor: use vi.stubEnv instead of process.env#205
yamcodes merged 6 commits intomainfrom
stub-envs

Conversation

@yamcodes
Copy link
Owner

@yamcodes yamcodes commented Oct 7, 2025

  • Replaced direct process.env assignments
  • Used vi.stubEnv for test environment
  • Added unstubEnvs: true to vitest config

Summary by CodeRabbit

  • Tests

    • Standardized env-var handling in tests using Vitest stubs for better isolation.
    • Simplified setup/teardown across test suites and reduced unused test imports.
  • Chores

    • Adopted project-based Vitest configs and enabled env-unstubbing.
    • Added a dev dependency to improve TypeScript path resolution.
  • Impact

    • No production behavior changes; improvements affect test infra and developer experience.

- Replaced direct process.env assignments
- Used vi.stubEnv for test environment
- Added unstubEnvs: true to vitest config
@changeset-bot
Copy link

changeset-bot bot commented Oct 7, 2025

⚠️ No Changeset found

Latest commit: e9a15f2

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@vercel
Copy link

vercel bot commented Oct 7, 2025

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Preview Comments Updated (UTC)
arkenv Ready Ready Preview Comment Oct 7, 2025 5:37pm

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Oct 7, 2025

Warning

Rate limit exceeded

@yamcodes has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 15 minutes and 1 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between b6e25c3 and e9a15f2.

📒 Files selected for processing (1)
  • apps/www/lib/utils/github.test.ts (7 hunks)

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

Walkthrough

Tests across multiple packages switch from directly mutating process.env to Vitest env stubbing APIs (e.g., vi.stubEnv, vi.unstubAllEnvs). Vitest configs add unstubEnvs and some projects move to project-style configs; one new package vitest config and a devDependency were added. No production code changes.

Changes

Cohort / File(s) Summary
Env stubbing in tests
apps/www/lib/utils/github.test.ts, packages/arkenv/src/index.test.ts, packages/vite-plugin/src/index.test.ts
Replace direct process.env mutations/restores with vi.stubEnv/vi.unstubAllEnvs and Vitest APIs; adjust setup/teardown accordingly; test behavior unchanged.
Vitest configuration updates
vitest.config.ts, apps/www/vitest.config.ts, packages/vite-plugin/vitest.config.ts, packages/arkenv/vitest.config.ts
Add test.unstubEnvs: true in root/www configs; switch some configs to defineProject (project-scoped exports), remove certain per-project fields in vite-plugin config, and add a new arkenv project config file.
Import cleanup in tests
apps/www/components/page/*.test.tsx, apps/www/components/ui/heading.test.tsx, apps/www/hooks/use-is-mobile.test.ts
Narrow and reorganize test imports (remove unused cleanup, lifecycle hooks) without changing test logic.
Vite-plugin package change
packages/vite-plugin/package.json
Add devDependency vite-tsconfig-paths to devDependencies.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Poem

I burrow through configs, nose to the ground,
Stubbed little envs now neatly bound.
I hop through projects, tidy each test den,
Unstub and restore — then do it again.
Small paws, big fixes, this rabbit grins. 🐇

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The provided title accurately reflects the main change—refactoring tests to use vi.stubEnv in place of direct process.env manipulation—while remaining concise and clear.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@github-actions github-actions bot added arkenv Changes to the `arkenv` npm package. @arkenv/vite-plugin Issues or Pull Requests involving the Vite plugin for ArkEnv www Improvements or additions to arkenv.js.org tests This issue or PR is about adding, removing or changing tests labels Oct 7, 2025
@yamcodes yamcodes marked this pull request as ready for review October 7, 2025 17:20
@pkg-pr-new
Copy link

pkg-pr-new bot commented Oct 7, 2025

Open in StackBlitz

npm i https://pkg.pr.new/arkenv@205
npm i https://pkg.pr.new/@arkenv/vite-plugin@205

commit: e9a15f2

cursor[bot]

This comment was marked as outdated.

- Fixed test setup and teardown
cursor[bot]

This comment was marked as outdated.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
packages/vite-plugin/src/index.test.ts (1)

50-65: Fix: alias "arkenv" during vite.build to avoid resolution errors in CI.

Vite’s build runs outside Vitest’s mock layer; vi.mock("arkenv") won’t intercept module resolution. Alias "arkenv" to a local stub for the build.

Apply this diff to the vite.build config and add a stub:

       await expect(
         vite.build({
           configFile: false,
           root: config.root,
           plugins: [arkenvPlugin(config.envSchema)],
           logLevel: "error",
+          resolve: {
+            alias: {
+              // Prevent workspace/package resolution during tests
+              arkenv: join(__dirname, "__stubs__/arkenv.ts"),
+            },
+          },
           build: {
             lib: {
               entry: "index.ts",
               formats: ["es"],
             },
             rollupOptions: {
               external: ["arkenv"],
             },
           },
         }),
       ).resolves.not.toThrow();

Add this file at packages/vite-plugin/src/stubs/arkenv.ts:

// Minimal stub; adjust if you need to observe calls
export const createEnv = (..._args: any[]) => {};
export default createEnv;

Alternative: ensure packages/arkenv has valid exports (main/module/exports) and is built before tests; otherwise the build process can’t resolve it. See verification script attached in package.json comment.

🧹 Nitpick comments (2)
packages/arkenv/vitest.config.ts (1)

3-7: Consider mirroring env cleanup here for clarity.

For explicitness in project-scoped runs, add test.unstubEnvs: true so behavior is clear even if run standalone.

 export default defineProject({
-  test: {
-    name: "arkenv",
-  },
+  test: {
+    name: "arkenv",
+    unstubEnvs: true,
+  },
 });
packages/vite-plugin/src/index.test.ts (1)

27-31: Redundant env/mocks cleanup; simplify to one place.

Given test.unstubEnvs: true at root, explicit vi.unstubAllEnvs() in both hooks is unnecessary. Also, afterEach(mockReset) already clears history; beforeEach(mockClear) can be dropped.

- beforeEach(() => {
-   // Clear environment variables and mock cleanup
-   vi.unstubAllEnvs();
-   mockCreateEnv.mockClear();
- });
+ beforeEach(() => {
+   mockCreateEnv.mockClear(); // or remove if you keep mockReset in afterEach
+ });

- afterEach(() => {
-   // Complete cleanup: restore environment and reset mocks
-   vi.unstubAllEnvs();
-   mockCreateEnv.mockReset();
- });
+ afterEach(() => {
+   mockCreateEnv.mockReset();
+ });

Also applies to: 33-37

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3ba266d and 36ccace.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (8)
  • apps/www/lib/utils/github.test.ts (6 hunks)
  • apps/www/vitest.config.ts (1 hunks)
  • packages/arkenv/src/index.test.ts (4 hunks)
  • packages/arkenv/vitest.config.ts (1 hunks)
  • packages/vite-plugin/package.json (1 hunks)
  • packages/vite-plugin/src/index.test.ts (3 hunks)
  • packages/vite-plugin/vitest.config.ts (1 hunks)
  • vitest.config.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.test.ts

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.test.ts: Place tests alongside source files and use the .test.ts suffix (e.g., create-env.test.ts, types.test.ts, errors.test.ts, utils.test.ts)
Use Vitest's describe/it structure in tests
Test both success and failure cases for environment validation and utilities
Mock process.env to cover different environment scenarios in tests
In tests, save and restore process.env in setup/teardown (beforeEach/afterEach) to avoid leakage between cases
Verify both runtime behavior and TypeScript types in tests

Files:

  • packages/vite-plugin/src/index.test.ts
  • packages/arkenv/src/index.test.ts
  • apps/www/lib/utils/github.test.ts
🧠 Learnings (4)
📓 Common learnings
Learnt from: CR
PR: yamcodes/arkenv#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-09-12T06:23:45.463Z
Learning: Applies to **/*.test.ts : Mock process.env to cover different environment scenarios in tests
Learnt from: CR
PR: yamcodes/arkenv#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-09-12T06:23:45.463Z
Learning: Applies to **/*.test.ts : In tests, save and restore process.env in setup/teardown (beforeEach/afterEach) to avoid leakage between cases
📚 Learning: 2025-09-12T06:23:45.463Z
Learnt from: CR
PR: yamcodes/arkenv#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-09-12T06:23:45.463Z
Learning: Applies to **/*.test.ts : In tests, save and restore process.env in setup/teardown (beforeEach/afterEach) to avoid leakage between cases

Applied to files:

  • packages/vite-plugin/src/index.test.ts
  • packages/arkenv/src/index.test.ts
  • apps/www/vitest.config.ts
  • apps/www/lib/utils/github.test.ts
📚 Learning: 2025-09-12T06:23:45.463Z
Learnt from: CR
PR: yamcodes/arkenv#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-09-12T06:23:45.463Z
Learning: Applies to **/*.test.ts : Mock process.env to cover different environment scenarios in tests

Applied to files:

  • packages/vite-plugin/src/index.test.ts
  • packages/arkenv/src/index.test.ts
  • apps/www/vitest.config.ts
  • apps/www/lib/utils/github.test.ts
📚 Learning: 2025-09-12T06:23:45.463Z
Learnt from: CR
PR: yamcodes/arkenv#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-09-12T06:23:45.463Z
Learning: Applies to **/*.test.ts : Test both success and failure cases for environment validation and utilities

Applied to files:

  • packages/arkenv/src/index.test.ts
🧬 Code graph analysis (2)
packages/vite-plugin/src/index.test.ts (2)
packages/vite-plugin/src/index.ts (1)
  • config (10-12)
packages/vite-plugin/src/__fixtures__/basic/index.ts (1)
  • config (2-5)
apps/www/lib/utils/github.test.ts (1)
apps/www/components/page/edit-on-github.test.tsx (1)
  • process (47-51)
🪛 GitHub Actions: tests
packages/vite-plugin/src/index.test.ts

[error] 1-1: Failed to resolve entry for package "arkenv". The package may have incorrect main/module/exports specified in its package.json.

packages/vite-plugin/package.json

[error] 1-1: Test failed: Failed to resolve entry for package "arkenv". The package may have incorrect main/module/exports specified in its package.json. See details in test output and ensure the package entry points are correctly defined.

🔇 Additional comments (9)
apps/www/vitest.config.ts (1)

17-18: Good addition: automatic env cleanup enabled.

unstubEnvs: true pairs well with vi.stubEnv usage and prevents cross-test leakage.

vitest.config.ts (1)

31-32: LGTM: repo-wide env isolation set.

unstubEnvs: true aligns with the switch to vi.stubEnv and removes the need for manual env restoring.

packages/vite-plugin/src/index.test.ts (1)

43-47: Nice: env setup uses vi.stubEnv per key.

This replaces direct mutations safely and pairs with unstubEnvs for isolation.

apps/www/lib/utils/github.test.ts (1)

31-31: Good migration to vi.stubEnv; confirm unset semantics for undefined.

Switching to vi.stubEnv is correct and isolates env across tests. For the “not configured” cases, verify that vi.stubEnv(NAME, undefined) removes the var (it should on Vitest ≥1.4).

If unsure, add a quick assertion:

vi.stubEnv("NEXT_PUBLIC_GITHUB_URL", undefined);
expect(process.env.NEXT_PUBLIC_GITHUB_URL).toBeUndefined();

Also applies to: 43-48, 59-60, 120-136, 146-147

packages/arkenv/src/index.test.ts (5)

14-19: LGTM! Proper environment variable stubbing.

The use of vi.stubEnv(..., undefined) to clear environment variables before each test is the correct approach for Vitest's environment stubbing API. This ensures proper test isolation.

Based on coding guidelines and learnings.


23-25: LGTM! Proper cleanup in afterEach.

The combination of vi.restoreAllMocks() and vi.unstubAllEnvs() ensures complete cleanup after each test, restoring both spies/mocks and environment variables to prevent test pollution.

Based on coding guidelines and learnings.


44-44: LGTM! Correct environment variable stubbing.

Using vi.stubEnv() instead of direct process.env assignment follows Vitest best practices and ensures proper test isolation with automatic cleanup via vi.unstubAllEnvs() in afterEach.

Based on coding guidelines and learnings.


56-56: LGTM! Correct environment variable stubbing.

Using vi.stubEnv() instead of direct process.env assignment follows Vitest best practices and ensures proper test isolation with automatic cleanup via vi.unstubAllEnvs() in afterEach.

Based on coding guidelines and learnings.


84-84: LGTM! Correct environment variable stubbing.

Using vi.stubEnv() instead of direct process.env assignment follows Vitest best practices and ensures proper test isolation with automatic cleanup via vi.unstubAllEnvs() in afterEach.

Based on coding guidelines and learnings.

- Added alias to arkenv package
- Enables easier testing
cursor[bot]

This comment was marked as outdated.

@yamcodes yamcodes merged commit 6c33a3d into main Oct 7, 2025
18 checks passed
@yamcodes yamcodes deleted the stub-envs branch October 7, 2025 17:37
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

@arkenv/vite-plugin Issues or Pull Requests involving the Vite plugin for ArkEnv arkenv Changes to the `arkenv` npm package. tests This issue or PR is about adding, removing or changing tests www Improvements or additions to arkenv.js.org

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant