Skip to content

refactor(vitest): convert to multi-project workspace with dynamic path resolution#808

Closed
senutpal wants to merge 5 commits intoCircuitVerse:mainfrom
senutpal:refactor/test-workspace-configuration
Closed

refactor(vitest): convert to multi-project workspace with dynamic path resolution#808
senutpal wants to merge 5 commits intoCircuitVerse:mainfrom
senutpal:refactor/test-workspace-configuration

Conversation

@senutpal
Copy link
Contributor

@senutpal senutpal commented Jan 16, 2026

Fixes #696 #697 #724 #772

Summary

Refactored test configuration from single-project to multi-project workspace supporting three isolated test environments (src, v0, v1).

Changes Made

1. New File: vitest.workspace.ts

Created multi-project workspace configuration with three isolated projects:

  • Uses fileURLToPath(import.meta.url) and path.join() for cross-platform path resolution
  • Each project has isolated alias resolution preventing cross-contamination
  • Each project uses its own setup file matching its source directory

2. Modified: package.json

Updated test scripts:

"test": "vitest --workspace vitest.workspace.ts --run --silent",
  • Added --workspace vitest.workspace.ts to use new configuration
  • Added --silent for cleaner output

3. Modified: vite.config.ts

Removed inline test configuration (lines 63-74):

// Test configuration is handled by vitest.workspace.ts
// Removed to avoid conflicts with workspace projects

When using --workspace flag, Vitest reads config from workspace file only. Inline test config would cause conflicts and duplicate test execution.

Rationale

The codebase has three parallel implementations. Each needs isolated test environments because:

  • Different import paths (# resolves differently)
  • Different component structures
  • Different versions of shared dependencies

When using --workspace, Vitest ignores inline test config. Keeping it causes:

  • Path resolution conflicts between projects
  • Duplicate test execution
  • Setup file conflicts

The extends: './vite.config.ts' in workspace projects preserves non-test configuration (plugins, build options).

Screenshots -

Screenshot 2026-01-16 173752

Code Understanding and AI Usage

Did you use AI assistance (ChatGPT, Claude, Copilot, etc.) to write any part of this code?

  • No, I wrote all the code myself
  • Yes, I used AI assistance (continue below)

If you used AI assistance:

  • I have reviewed every single line of the AI-generated code
  • I can explain the purpose and logic of each function/component I added
  • I have tested edge cases and understand how the code handles them
  • I have modified the AI output to follow this project's coding standards and conventions

Explain your implementation approach:

The workspace configuration was designed to maintain backward compatibility with existing tests while adding isolation. Each project extends the main vite.config.ts to inherit plugins and build settings, but overrides resolve.alias and test.setupFiles for project-specific behavior. The dynamic path resolution using fileURLToPath and path.join ensures cross-platform compatibility without hardcoded paths.


Checklist before requesting a review

  • I have added proper PR title and linked to the issue
  • I have performed a self-review of my code
  • I can explain the purpose of every function, class, and logic block I added
  • I understand why my changes work and have tested them thoroughly
  • I have considered potential edge cases and how my code handles them
  • If it is a core feature, I have added thorough tests
  • My code follows the project's style guidelines and conventions

Note: Please check Allow edits from maintainers if you would like us to assist in the PR.

Summary by CodeRabbit

  • Tests
    • Added a multi-version test workspace and updated test runner to run workspaces with quieter output; expanded test scaffolding and environment mocks across simulator suites.
  • Chores
    • Added CI workflow to run tests on push/PR; updated config to support version-aware paths and locale resolution; adjusted lint/type includes for the new workspace.
  • Stability
    • Centralized test setup with teardown/error-suppression and DOM/API shims for more reliable test execution.

✏️ Tip: You can customize this high-level summary in your review settings.

@netlify
Copy link

netlify bot commented Jan 16, 2026

Deploy Preview for circuitverse ready!

Name Link
🔨 Latest commit 130f490
🔍 Latest deploy log https://app.netlify.com/projects/circuitverse/deploys/696b96906df44900070c8b16
😎 Deploy Preview https://deploy-preview-808--circuitverse.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.
Lighthouse
Lighthouse
1 paths audited
Performance: 43 (🔴 down 1 from production)
Accessibility: 73 (no change from production)
Best Practices: 92 (no change from production)
SEO: 82 (no change from production)
PWA: -
View the detailed breakdown and full score reports

To edit notification comments on pull requests, go to your Netlify project configuration.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jan 16, 2026

Walkthrough

Adds a Vitest workspace and CI test workflow, updates test wiring and many simulator tests, and adjusts build/config files. Key facts: new vitest.workspace.ts exporting two per-version workspace configs (src, v1); package.json scripts.test changed to vitest --workspace vitest.workspace.ts --run --silent; vite.config.ts updated (named vueI18n import, version-aware locale/include and path aliases, removed unused plugin, test block removed); many simulator spec files and vitestSetup.ts replaced/augmented with Vitest-compatible mocks and typed setup including error-suppression; .eslintrc.js and tsconfig.node.json updated to ignore/include the workspace file; .github/workflows/vitest.yml added; src/simulator/src/node.js introduced local NODE_* constants and re-exposed them on window.

Possibly related PRs

Suggested labels

GSOC'24

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly describes the main change: converting to a multi-project Vitest workspace with dynamic path resolution, which aligns with the primary modifications to the test configuration setup.
Linked Issues check ✅ Passed The PR addresses issue #772 by implementing isolated Vitest workspaces for the three implementations (src, v1) with separate path aliases and setup files, enabling successful test execution via the new workspace-based configuration.
Out of Scope Changes check ✅ Passed All changes are scoped to test infrastructure and setup. Updates to src/simulator/src/node.js and associated spec files align with resolving test failures and establishing the workspace configuration required for the PR objectives.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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.

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: 1

🤖 Fix all issues with AI agents
In `@vitest.workspace.ts`:
- Around line 8-72: The workspace configs in vitest.workspace.ts extend the base
vite.config.ts which reads process.env.VITE_SIM_VERSION (defaulting to "v0"), so
the vueI18n plugin in the base config will always load v0 locales for every
workspace; fix by ensuring each workspace sets VITE_SIM_VERSION appropriately or
by moving version-dependent plugin configuration into each workspace block:
update the v1 workspace to set VITE_SIM_VERSION="v1" (or equivalent
per-workspace env support) or remove the vueI18n/plugin config from
vite.config.ts and add it into each workspace override so the plugin uses the
workspace's resolve.alias and correct version-specific locales (refer to
process.env.VITE_SIM_VERSION, vite.config.ts, and the workspace objects in
vitest.workspace.ts).
📜 Review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0e58e46 and 1e6071b.

📒 Files selected for processing (3)
  • package.json
  • vite.config.ts
  • vitest.workspace.ts
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2026-01-07T19:39:24.443Z
Learnt from: naman79820
Repo: CircuitVerse/cv-frontend-vue PR: 729
File: package.json:56-56
Timestamp: 2026-01-07T19:39:24.443Z
Learning: In Node 18 environments (e.g., this repo cv-frontend-vue), pin cross-env to 7.x (e.g., ^7.0.3) because cross-env 10.x requires Node >= 20. When editing package.json, ensure cross-env version stays within 7.x to maintain compatibility with Node 18.

Applied to files:

  • package.json
🔇 Additional comments (4)
vite.config.ts (2)

35-45: LGTM: formatting-only change.
No behavioral impact expected; reads cleaner.


63-74: Good consolidation of test config into workspace.
Keeping Vitest config in one place should prevent conflicts.

package.json (1)

14-14: LGTM: test script aligned with workspace config.

vitest.workspace.ts (1)

1-27: Nice workspace layout and cross‑platform path resolution.
Per‑project alias + setupFiles look clean and isolated.

✏️ Tip: You can disable this entire section by setting review_details to false in your review settings.

@senutpal senutpal force-pushed the refactor/test-workspace-configuration branch from 7a3a363 to 93ad29e Compare January 17, 2026 06:28
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: 4

Caution

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

⚠️ Outside diff range comments (5)
src/simulator/src/node.js (1)

399-520: Address Biome noFallthrough and noRedeclare lint errors in switch statement.

The function has two var i declarations at lines 393 and 441 within the same scope, which triggers the noRedeclare rule. The switch statement at lines 441-520 contains intentional fallthroughs without biome-ignore directives, which triggers noFallthrough warnings. Change the loop counter at line 441 from var i to let i to avoid the redeclaration issue, and add biome-ignore lint/suspicious/noFallthroughSwitchClause comments before the fallthrough cases at lines 472 (NODE_INPUT) and 482 (NODE_INTERMEDIATE).

v1/src/simulator/src/node.js (1)

399-520: Resolve switch fallthroughs and variable redeclarations flagged by Biome.

The switch statement has intentional fallthroughs between NODE_OUTPUT and NODE_INPUT, and between NODE_INPUT and NODE_INTERMEDIATE. Additionally, the function declares var i twice in the same scope (lines 393 and 441), triggering Biome's noRedeclare rule. Both issues will cause lint failures.

Add // biome-ignore lint/suspicious/noFallthroughSwitchClause before each fallthrough case and change both var i declarations to let i to resolve this.

Suggested fix
-        for (var i = 0; i < this.connections.length; i++) {
+        for (let i = 0; i < this.connections.length; i++) {
             if (this.connections[i].value !== undefined) {
                 this.connections[i].value = undefined
                 simulationArea.simulationQueue.add(this.connections[i])
             }
         }
         ...
-        for (var i = 0; i < this.connections.length; i++) {
+        for (let i = 0; i < this.connections.length; i++) {
             const node = this.connections[i]

             switch (node.type) {
+                // biome-ignore lint/suspicious/noFallthroughSwitchClause
                 case NODE_OUTPUT:
                     ...
                 // Fallthrough. NODE_OUTPUT propagates like a contention checked NODE_INPUT
+                // biome-ignore lint/suspicious/noFallthroughSwitchClause
                 case NODE_INPUT:
                     ...
                 // Fallthrough. NODE_INPUT propagates like a bitwidth checked NODE_INTERMEDIATE
+                // biome-ignore lint/suspicious/noFallthroughSwitchClause
                 case NODE_INTERMEDIATE:
                     ...
                 default:
                     break
             }
         }
src/simulator/spec/gates.spec.js (1)

55-104: Avoid test-order coupling by loading circuit data in setup.
runAll defaults to globalScope, which is initialized by load(circuitData). If the “load circuitData” test is skipped or order changes, later tests can fail or flake. Load once in beforeAll (or per test) to make execution order irrelevant.

🛠️ Suggested fix
     beforeAll(async () => {
         pinia = createPinia()
         setActivePinia(pinia)
@@
         mount(simulator, {
             global: {
                 plugins: [pinia, router, i18n, vuetify],
             },
             attachTo: elem,
         })

         setup()
+        load(circuitData)
     })
src/simulator/spec/decoders-plexers.spec.js (1)

55-104: Remove the implicit dependency on test order.
runAll relies on globalScope, which is initialized by load(circuitData). If the load test doesn’t run first (or is filtered), later tests can fail. Load the circuit data in beforeAll (or in each test) to make tests independent.

🛠️ Suggested fix
     beforeAll(async () => {
         pinia = createPinia()
         setActivePinia(pinia)
@@
         mount(simulator, {
             global: {
                 plugins: [pinia, router, i18n, vuetify],
             },
             attachTo: elem,
         })

         setup()
+        load(circuitData)
     })
src/simulator/spec/sequential.spec.js (1)

55-104: Make tests independent by loading the circuit data in setup.
Later tests depend on globalScope being initialized by load(circuitData). If the “load circuitData” test is skipped or reordered, the rest can fail. Load once in beforeAll (or per test) to avoid order coupling.

🛠️ Suggested fix
     beforeAll(async () => {
         pinia = createPinia()
         setActivePinia(pinia)
@@
         mount(simulator, {
             global: {
                 plugins: [pinia, router, i18n, vuetify],
             },
             attachTo: elem,
         })

         setup()
+        load(circuitData)
     })
🤖 Fix all issues with AI agents
In `@src/simulator/spec/vitestSetup.ts`:
- Around line 31-100: There are two afterAll hooks causing a timing gap where
cleanup happens before isTearingDown is set, so expected teardown errors are not
suppressed; merge the teardown logic into a single afterAll that first sets
isTearingDown = true, then performs cleanup (clear timers, useRealTimers,
clearAllMocks, restoreAllMocks) and only after that unregisters the process
handlers (process.off for 'unhandledRejection' and 'uncaughtException'); update
or remove the earlier afterAll block so all cleanup uses the consolidated
afterAll referencing isTearingDown, handleUnhandledRejection,
handleUncaughtException, and suppressedPatterns.

In `@v1/src/simulator/spec/bitConvertor.spec.js`:
- Line 52: The describe block currently reads "data dir working" but these tests
are for bitConvertor; rename the describe block string from "data dir working"
to "bitConvertor" so the test suite accurately reflects the tested module
(update the describe declaration that currently appears as describe('data dir
working', ...) to describe('bitConvertor', ...)).

In `@v1/src/simulator/spec/combinationalAnalysis.spec.js`:
- Around line 114-120: The test mutates the shared testData.AndGate object
causing cross-test contamination; fix it by creating a local deep clone of
testData.AndGate (e.g., using structuredClone or
JSON.parse(JSON.stringify(testData.AndGate))) at the start of the test, modify
labels on that cloned object instead of testData.AndGate, and pass the clone to
runAll so the original testData stays unchanged (this prevents leaking state
into gates.spec.js which imports the same module).

In `@v1/src/simulator/spec/vitestSetup.ts`:
- Around line 92-95: The teardown sets isTearingDown after unregistering the
error handlers, making shouldSuppressError ineffective during cleanup; in the
afterAll block set isTearingDown = true before performing any cleanup that may
trigger handlers (so shouldSuppressError will see the flag), keep the handlers
(handleUnhandledRejection and handleUncaughtException) registered while cleanup
runs, and only call process.off('unhandledRejection', handleUnhandledRejection)
and process.off('uncaughtException', handleUncaughtException) after cleanup
completes so the handlers can suppress errors during teardown.
🧹 Nitpick comments (9)
src/simulator/spec/bitConvertor.spec.js (1)

112-116: Prefer deterministic input in tests.

Random inputs make failures harder to reproduce.

🧪 Suggested tweak
-        const randomBaseValue = Math.floor(Math.random() * 100)
-        console.log('Testing for Base Value --> ', randomBaseValue)
-        expect(() => setBaseValues(randomBaseValue)).not.toThrow()
+        const baseValue = 42
+        expect(() => setBaseValues(baseValue)).not.toThrow()
src/simulator/spec/combinationalAnalysis.spec.js (2)

92-92: Consider using window.globalScope for consistency with TypeScript declarations.

Based on learnings, globalScope should be declared on the window object rather than using global.globalScope. This is inconsistent with the pattern established in vitestSetup.ts where window properties are properly typed and assigned.

Suggested change
-        global.globalScope = global.globalScope || {}
+        window.globalScope = window.globalScope || {}

94-101: Mounted component reference is discarded; consider cleanup.

The mount() call returns a wrapper that isn't stored. While this may work for beforeAll, if tests modify component state, there's no way to access or unmount it. Consider storing the wrapper if you need to interact with it or ensure proper cleanup.

v1/src/simulator/spec/vitestSetup.ts (1)

37-42: Duplicate cleanup calls across two afterAll hooks.

The cleanup methods (vi.clearAllTimers(), vi.useRealTimers(), vi.clearAllMocks(), vi.restoreAllMocks()) are called in both afterAll blocks (lines 38-41 and 96-99). This redundancy is harmless but unnecessary. Consider consolidating into a single afterAll hook.

Consolidate afterAll hooks
-// Restore real timers and cleanup after all tests
-afterAll(() => {
-    vi.clearAllTimers()
-    vi.useRealTimers()
-    vi.clearAllMocks()
-    vi.restoreAllMocks()
-})
-
 // Patterns for errors that should be suppressed during teardown
 const suppressedPatterns = [
     ...
 ]
 
 ...
 
 // Unregister error handlers and suppress expected teardown errors
 afterAll(() => {
     isTearingDown = true
     process.off('unhandledRejection', handleUnhandledRejection)
     process.off('uncaughtException', handleUncaughtException)
     vi.clearAllTimers()
     vi.useRealTimers()
     vi.clearAllMocks()
     vi.restoreAllMocks()
 })

Also applies to: 92-100

v1/src/simulator/spec/decoders-plexers.spec.js (1)

15-100: Consider extracting shared test scaffolding to reduce duplication.

This entire block (mocks, beforeAll setup with Pinia/Router/mount) is duplicated across multiple spec files (gates.spec.js, subCircuit.spec.js, bitConvertor.spec.js, etc.). Since the workspace already has a vitestSetup.ts, consider moving common mocks and setup utilities there or to a shared test helper module.

This would:

  • Reduce maintenance burden when mocks need updating
  • Ensure consistency across test suites
  • Make individual spec files more focused on their actual tests
v1/src/simulator/spec/bitConvertor.spec.js (1)

112-116: Remove console.log from test.

The console.log statement adds noise to test output, especially with --silent mode in the test script. If debugging info is needed, consider using Vitest's built-in logging or removing it for CI.

Remove console.log
     test('function setBaseValues working', () => {
         const randomBaseValue = Math.floor(Math.random() * 100)
-        console.log('Testing for Base Value --> ', randomBaseValue)
         expect(() => setBaseValues(randomBaseValue)).not.toThrow()
     })
v1/src/simulator/spec/sequential.spec.js (1)

15-100: Consolidate shared test harness & confirm setup() completion

The mocks + mount boilerplate are repeated across multiple spec files; consider extracting a shared helper to reduce drift. Also, please confirm whether setup() performs async work—if it does, await it in beforeAll to avoid partial initialization during tests.

v1/src/simulator/spec/data.spec.js (1)

113-160: Reduce order-dependence across tests

Several tests assume state produced by earlier tests (e.g., load(...) before scheduleBackup, undo, redo). Consider isolating state per test (e.g., beforeEach with a fresh load/reset) to avoid flaky behavior if sequencing changes.

src/simulator/spec/gates.spec.js (1)

15-99: Consider extracting the shared test harness into a helper.
The mock/mount boilerplate here is repeated across multiple spec files; a shared helper (or centralized Vitest setup) would reduce duplication and keep mocks consistent.

- Add ignorePatterns for config files in eslint
- Add vitest.workspace.ts to tsconfig.node.json
- Fix vueI18n, path aliases for 'src' workspace
- Refactor vitest.workspace.ts to use factory function
@senutpal senutpal force-pushed the refactor/test-workspace-configuration branch from 93ad29e to 5671610 Compare January 17, 2026 06:36
@tachyons
Copy link
Member

Could you add this to CI as well so that we can validate on each pull request ?

- Run tests on push to main and all pull requests
- Use Node.js 22 with npm caching for performance
- Enable concurrency control to cancel duplicate runs
- Add github-actions reporter for inline PR annotations
- Set 10-minute timeout for test execution
@senutpal
Copy link
Contributor Author

done @tachyons

@tachyons
Copy link
Member

@senutpal Tests are red, could you add the fixes for the tests in this PR so that we can merge this with green CI

@tachyons
Copy link
Member

Also v0 is symlinked to src. So there is no need to run tests for that dir separately

@senutpal
Copy link
Contributor Author

all done @tachyons

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

🤖 Fix all issues with AI agents
In `@src/simulator/spec/bitConvertor.spec.js`:
- Line 52: The test suite describe block currently reads 'data dir working'
which is a copy-paste error; update the describe block in
src/simulator/spec/bitConvertor.spec.js to a correct name reflecting the tests
(e.g., "bitConvertor utilities" or "BitConvertor") so the suite matches the file
purpose and tests for the bit converter functions; locate the describe(...) at
the top of the file and replace the string accordingly.

In `@src/simulator/spec/data.spec.js`:
- Around line 200-205: The test "OpenOffline working" uses optional chaining on
DOM selections which can mask missing elements; update the test around
openOffline() to explicitly query and assert the presence of the elements (e.g.,
the '#openProjectDialog input' element and the '#Open_offline_btn' element)
before calling click() so failures surface—locate the test function named
"OpenOffline working" and the openOffline() call, replace or augment the lines
with explicit queries and expect/assert statements that the elements are not
null (or throw) and only then call element.click(), then keep the final
expectation on globalScope.id.
♻️ Duplicate comments (4)
src/simulator/spec/vitestSetup.ts (1)

36-42: Consolidate teardown so suppression applies during cleanup.

The first afterAll runs before isTearingDown is set, so teardown errors won’t be suppressed; cleanup is also duplicated. Merge into a single teardown where isTearingDown is set before cleanup and handlers are removed afterward.

🛠️ Suggested consolidation
-// Restore real timers and cleanup after all tests
-afterAll(() => {
-    vi.clearAllTimers()
-    vi.useRealTimers()
-    vi.clearAllMocks()
-    vi.restoreAllMocks()
-})
+// Restore real timers and cleanup after all tests; suppress expected teardown errors
+afterAll(() => {
+    isTearingDown = true
+    vi.clearAllTimers()
+    vi.useRealTimers()
+    vi.clearAllMocks()
+    vi.restoreAllMocks()
+    process.off('unhandledRejection', handleUnhandledRejection)
+    process.off('uncaughtException', handleUncaughtException)
+})
...
-// Unregister error handlers and suppress expected teardown errors
-afterAll(() => {
-    isTearingDown = true
-    process.off('unhandledRejection', handleUnhandledRejection)
-    process.off('uncaughtException', handleUncaughtException)
-    vi.clearAllTimers()
-    vi.useRealTimers()
-    vi.clearAllMocks()
-    vi.restoreAllMocks()
-})

Also applies to: 92-99

v1/src/simulator/spec/vitestSetup.ts (1)

36-42: Keep handlers registered while teardown cleanup runs.

isTearingDown is set, but handlers are removed before cleanup, so suppression can’t catch teardown errors. Reorder cleanup ahead of process.off(...).

🛠️ Suggested reorder
 afterAll(() => {
     isTearingDown = true
-    process.off('unhandledRejection', handleUnhandledRejection)
-    process.off('uncaughtException', handleUncaughtException)
     vi.clearAllTimers()
     vi.useRealTimers()
     vi.clearAllMocks()
     vi.restoreAllMocks()
+    process.off('unhandledRejection', handleUnhandledRejection)
+    process.off('uncaughtException', handleUncaughtException)
 })

Also applies to: 92-99

v1/src/simulator/spec/bitConvertor.spec.js (1)

52-52: Rename the suite to match the BitConvertor tests.

✏️ Suggested rename
-describe('data dir working', () => {
+describe('BitConvertor Testing', () => {
v1/src/simulator/spec/combinationalAnalysis.spec.js (1)

115-120: Avoid mutating shared test fixtures (clone before edits).

Line 115-119 mutates testData.AndGate in-place, which can leak into other specs that import the same JSON and make tests order-dependent. Clone before editing and pass the clone into runAll.

♻️ Proposed fix
-        testData.AndGate.groups[0].inputs[0].label = 'A'
-        testData.AndGate.groups[0].inputs[1].label = 'B'
-        testData.AndGate.groups[0].outputs[0].label = 'AB'
-
-        const result = runAll(testData.AndGate)
+        const andGate = JSON.parse(JSON.stringify(testData.AndGate))
+        andGate.groups[0].inputs[0].label = 'A'
+        andGate.groups[0].inputs[1].label = 'B'
+        andGate.groups[0].outputs[0].label = 'AB'
+
+        const result = runAll(andGate)
🧹 Nitpick comments (12)
v1/src/simulator/spec/sequential.spec.js (1)

51-100: Add teardown to unmount the simulator and remove the mount node.

This avoids DOM leakage across test files when isolation is disabled or shared workers are used.

♻️ Suggested teardown
 describe('Simulator Sequential Element Testing', () => {
     let pinia
     let router
+    let wrapper
+    let mountEl
@@
-        const elem = document.createElement('div')
+        const elem = document.createElement('div')
+        mountEl = elem
@@
-        mount(simulator, {
+        wrapper = mount(simulator, {
             global: {
                 plugins: [pinia, router, i18n, vuetify],
             },
             attachTo: elem,
         })
@@
         setup()
     })
+
+    afterAll(() => {
+        wrapper?.unmount()
+        mountEl?.remove()
+    })
v1/src/simulator/spec/decoders-plexers.spec.js (1)

1-100: Consider extracting shared test setup/mocks into a helper.

The setup here mirrors multiple spec files; a shared helper would reduce duplication and keep fixes in sync.

v1/src/simulator/spec/gates.spec.js (1)

15-49: Consider extracting shared test scaffolding to reduce duplication.

This mock setup block (tauri, ResizeObserver, canvas context, codemirror) is duplicated nearly verbatim across all spec files in the PR. Extract these mocks to a shared setup file (e.g., vitestSetup.ts) and configure it in your Vitest workspace to run automatically.

Note: The canvas context mock here is missing methods that data.spec.js includes (e.g., rect, save, restore, translate, scale, measureText, setLineDash, getImageData, rotate, putImageData, drawImage, bezierCurveTo). If any test indirectly triggers these methods, it will fail with "not a function" errors.

src/simulator/spec/data.spec.js (1)

36-64: This canvas mock is the most comprehensive—use it as the shared template.

This file includes additional canvas context methods (rect, save, restore, translate, scale, measureText, setLineDash, getImageData, rotate, putImageData, drawImage, bezierCurveTo) that other spec files lack. When consolidating to a shared setup, use this version to avoid "method is not a function" errors in tests that trigger these canvas operations.

src/simulator/spec/bitConvertor.spec.js (1)

112-116: Remove console.log from test.

The console.log statement adds noise to test output. If you need to debug test values, use Vitest's verbose mode or debugging tools instead.

♻️ Suggested fix
     test('function setBaseValues working', () => {
         const randomBaseValue = Math.floor(Math.random() * 100)
-        console.log('Testing for Base Value --> ', randomBaseValue)
         expect(() => setBaseValues(randomBaseValue)).not.toThrow()
     })
src/simulator/spec/sequential.spec.js (1)

15-49: Shared mock scaffolding duplicated here too.

Same duplication concern as noted for other spec files. The canvas mock here uses the basic set of methods, which may be insufficient if sequential element tests indirectly trigger additional canvas operations.

src/simulator/spec/subCircuit.spec.js (1)

15-49: Same mock scaffolding duplication.

As with other spec files, this boilerplate should be consolidated into a shared setup file.

v1/src/simulator/spec/data.spec.js (2)

26-76: Significant mock duplication across test files—consider extracting to a shared setup module.

This file and the other spec files (misc.spec.js, complexCircuit.spec.js, combinationalAnalysis.spec.js, decoders-plexers.spec.js) all contain nearly identical mock code (~90 lines) for tauri events, ResizeObserver, HTMLCanvasElement.getContext, and codemirror modules. This v1 version has the most comprehensive canvas mock with additional methods (e.g., getSerializedSvg, getImageData, drawImage, bezierCurveTo).

Extract these mocks to a shared test utility file (e.g., testSetupMocks.ts) and import it in each spec. This reduces maintenance burden and ensures consistency across test files.


200-205: Potential brittleness in DOM selector assertions.

The test relies on specific DOM selectors (#openProjectDialog input, #Open_offline_btn) which may break if the component structure changes. Consider adding data-testid attributes to the component for more robust test selectors.

src/simulator/spec/complexCircuit.spec.js (1)

53-53: Misleading describe block name—should reflect complex circuit testing.

The describe block is named 'data dir working' but this file tests complex circuits (ripple carry adder, ALU). Consider renaming to something more descriptive like 'Complex Circuit Testing' or 'Simulator Complex Circuit Testing'.

Suggested fix
-describe('data dir working', () => {
+describe('Simulator Complex Circuit Testing', () => {
src/simulator/spec/combinationalAnalysis.spec.js (1)

114-121: Test mutates shared testData object—could cause test pollution.

Lines 115-117 directly mutate testData.AndGate.groups[0].inputs[0].label, etc. If this testData object is reused in other tests (within this file or across the test suite), these mutations persist and may cause unexpected behavior or flaky tests.

Consider deep-cloning the test data before mutation:

Suggested fix
 test('testing Combinational circuit', () => {
-    testData.AndGate.groups[0].inputs[0].label = 'A'
-    testData.AndGate.groups[0].inputs[1].label = 'B'
-    testData.AndGate.groups[0].outputs[0].label = 'AB'
+    const andGateData = structuredClone(testData.AndGate)
+    andGateData.groups[0].inputs[0].label = 'A'
+    andGateData.groups[0].inputs[1].label = 'B'
+    andGateData.groups[0].outputs[0].label = 'AB'

-    const result = runAll(testData.AndGate)
+    const result = runAll(andGateData)
     expect(result.summary.passed).toBe(3)
 })
src/simulator/spec/decoders-plexers.spec.js (1)

1-100: Consistent test scaffolding—duplicated setup should be centralized.

This file follows the same pattern as other spec files with identical mocks and setup code. As noted in the v1/data.spec.js review, this ~90 lines of duplicated code across all spec files should be extracted to a shared test utility module to improve maintainability.

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: 0

Caution

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

⚠️ Outside diff range comments (2)
v1/src/simulator/src/node.js (1)

399-452: Switch to let for loop variables in resolve().

Two loops in the resolve() function redeclare var i in the same function scope, triggering Biome's noRedeclare rule. let is block-scoped and will resolve this:

🔧 Proposed fix
-            for (var i = 0; i < this.connections.length; i++) {
+            for (let i = 0; i < this.connections.length; i++) {
                 ...
-        for (var i = 0; i < this.connections.length; i++) {
+        for (let i = 0; i < this.connections.length; i++) {
                 ...
src/simulator/src/node.js (1)

399-452: Replace var with let in resolve() loops to avoid redeclaration.

The resolve() method declares var i twice in the same function scope (lines 400 and 450), which violates Biome's noRedeclare rule. Since var is function-scoped, both loop variables collide. Switching to let creates block scope for each loop.

🔧 Proposed fix
-            for (var i = 0; i < this.connections.length; i++) {
+            for (let i = 0; i < this.connections.length; i++) {
                 ...
-        for (var i = 0; i < this.connections.length; i++) {
+        for (let i = 0; i < this.connections.length; i++) {
                 ...
♻️ Duplicate comments (2)
v1/src/simulator/src/node.js (1)

454-520: Add explicit fallthrough annotations for Biome.

Biome flags these intentional fallthroughs. Add explicit biome-ignore (or the accepted fallthrough marker) so CI doesn’t fail on lint.

🧹 Suggested suppression pattern
-                case NODE_OUTPUT:
+                // biome-ignore lint/suspicious/noFallthroughSwitchClause
+                case NODE_OUTPUT:
                     ...
-                case NODE_INPUT:
+                // biome-ignore lint/suspicious/noFallthroughSwitchClause
+                case NODE_INPUT:
                     ...
-                case NODE_INTERMEDIATE:
+                // biome-ignore lint/suspicious/noFallthroughSwitchClause
+                case NODE_INTERMEDIATE:
src/simulator/src/node.js (1)

454-520: Add explicit fallthrough annotations for Biome.

Biome flags these intentional fallthroughs. Add explicit biome-ignore (or the accepted fallthrough marker) so CI doesn’t fail on lint.

🧹 Suggested suppression pattern
-                case NODE_OUTPUT:
+                // biome-ignore lint/suspicious/noFallthroughSwitchClause
+                case NODE_OUTPUT:
                     ...
-                case NODE_INPUT:
+                // biome-ignore lint/suspicious/noFallthroughSwitchClause
+                case NODE_INPUT:
                     ...
-                case NODE_INTERMEDIATE:
+                // biome-ignore lint/suspicious/noFallthroughSwitchClause
+                case NODE_INTERMEDIATE:
🧹 Nitpick comments (1)
src/simulator/src/node.js (1)

125-131: Guard global constant exposure for non‑browser runtimes.

Top‑level window.* assignments will throw if this module is imported under a Node/Vitest environment: "node" or SSR. Consider using globalThis or a guarded block.

🛠️ Proposed refactor
- window.NODE_INPUT = NODE_INPUT
- window.NODE_OUTPUT = NODE_OUTPUT
- window.NODE_INTERMEDIATE = NODE_INTERMEDIATE
+ const globalTarget = typeof window !== 'undefined' ? window : globalThis
+ globalTarget.NODE_INPUT = NODE_INPUT
+ globalTarget.NODE_OUTPUT = NODE_OUTPUT
+ globalTarget.NODE_INTERMEDIATE = NODE_INTERMEDIATE

@senutpal
Copy link
Contributor Author

@tachyons ci is green now

Comment on lines -27 to -28
let pinia;
let router;
Copy link
Member

Choose a reason for hiding this comment

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

@senutpal Could you revert all unrelated changes including semicolon removal. Because it makes PR too big

Copy link
Contributor Author

@senutpal senutpal Jan 24, 2026

Choose a reason for hiding this comment

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

@tachyons my editor auto-formats on save because .prettierrc has semi: false, so it keeps undoing the fixes i make. it’s getting pretty hectic to manually revert those changes. is there any git workflow to separate formatting changes from actual logic changes, or some interactive/diff-based way to undo only the formatting ?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@tachyons i am thinking to open a new clean pr what do you say ?

for (var i = 0; i < this.parent.scope.wires.length; i++) {
if (this.parent.scope.wires[i].checkConvergence(this)) {
if (
this.parent.scope.wires[i].node1 === this ||
Copy link
Member

Choose a reason for hiding this comment

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

@senutpal. No need for this as it is correctly fixed in #852.

@senutpal senutpal closed this Jan 26, 2026
@senutpal senutpal deleted the refactor/test-workspace-configuration branch January 26, 2026 13:06
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

🐞 Bug: Wire routing parity issue: cv-frontend-vue does not support orthogonal (zig-zag) wires

3 participants