Skip to content

feat: address mocking failures#235

Merged
goosewobbler merged 44 commits intomainfrom
fix/getMockImplementation
Apr 22, 2026
Merged

feat: address mocking failures#235
goosewobbler merged 44 commits intomainfrom
fix/getMockImplementation

Conversation

@goosewobbler
Copy link
Copy Markdown
Contributor

No description provided.

…t mock implementation

- Implemented `getMockImplementation` method in the mock function to allow users to access the current mock implementation.
- Updated the `Mock` interface in `types.ts` to include the new method.
- Added tests to verify the functionality of `getMockImplementation`, ensuring it returns the correct implementation or undefined when none is set.
@goosewobbler goosewobbler added scope:shared Shared utilities and infrastructure bump:patch Release a patch version labels Apr 19, 2026
@github-actions
Copy link
Copy Markdown
Contributor

github-actions Bot commented Apr 19, 2026

Release Preview — @wdio/native-spy 1.0.10

Scope: @wdio/native-spy

This PR is labeled for a patch release.

This PR will trigger the following release when merged:

Packages

Package Version
@wdio/native-spy 1.0.10

Changelog

@wdio/native-spy wdio-native-spy@v1.0.9 → 1.0.10

Added

  • enhance mock function state management and last call tracking (native-spy)
  • enhance mock function with original implementation support (native-spy)
  • add test for initial implementation retrieval in mock function (native-spy)
  • add getMockImplementation method to retrieve current mock implementation (native-spy)

Changed

  • remove redundant implementation reset in mock functions (native-spy)
  • standardize package.json files array formatting across multiple packages

Fixed

  • correct mock return value handling (native-spy)
  • improve mock function behavior and state management (native-spy)

Tags

  • wdio-native-spy@v1.0.10

Updated automatically by ReleaseKit

@greptile-apps
Copy link
Copy Markdown
Contributor

greptile-apps Bot commented Apr 19, 2026

Greptile Summary

This PR addresses mocking failures by introducing a new @wdio/native-spy package (a lightweight vitest-compatible mock implementation), refactoring the electron-service to use a shared mockFactory.ts with proper Error-serialisation across CDP, adding class mocking support for Electron, and implementing a JavaScript-only Tauri mocking layer via window.__wdio_mocks__ and invoke interception. CI workflows are also updated with a new vscode-server-action version and revised archive actions.

Confidence Score: 4/5

Safe to merge after addressing the debug console logs and clarifying mock-reuse reset behaviour in the Tauri service.

The core P0/P1 issues from previous review rounds (Error serialisation, mockReturnThis chaining, implementationFn dispatch precedence) appear addressed. Remaining findings are all P2: debug TEST log noise in production init, double-round-trip inefficiency in resetAllMocks, and a mock-reuse semantic divergence from electron.

packages/tauri-service/src/commands/mock.ts (double-reset + reuse semantics), packages/tauri-plugin/guest-js/index.ts (debug log cleanup)

Important Files Changed

Filename Overview
packages/native-spy/src/mock.ts New standalone vitest-compatible mock implementation. Dispatch-order issue (defaultRejectedValue before implementationFn) persists from prior threads. mockReturnValueOnce/mockResolvedValueOnce correctly no longer clear implementationFn. mockRestored branch correctly sits after all value branches.
packages/tauri-service/src/mock.ts New Tauri mock factory. mockRejectedValue/mockRejectedValueOnce now correctly serialize Error objects. mockReturnThis correctly returns mock for chaining. Core logic sound but shares double-reset issue with resetAllMocks.
packages/tauri-service/src/commands/mock.ts New command handlers for mock, clearAllMocks, resetAllMocks, restoreAllMocks. Two issues: resetAllMocks/restoreAllMocks double-reset inner mocks (N+1 browser round-trips), and mock() resets existing mock state on reuse, diverging from electron-service behaviour.
packages/electron-service/src/mockFactory.ts New shared mock method factory for electron. mockRejectedValue/mockRejectedValueOnce now correctly handle Error objects for both api and prototype accessor kinds. Clean refactor from duplicated per-mock code.
packages/tauri-plugin/guest-js/index.ts Plugin frontend API with invoke interception and console forwarding. Two debug TEST: console calls left in production init(). Init messages are intentionally emitted twice (before and after forwarding is active).
e2e/test/electron/mocking.spec.ts Comprehensive electron mocking e2e tests. The beforeEach clipboard setup in restoreAllMocks suite has been correctly re-added, addressing the previous flakiness concern.
packages/native-spy/test/spy.spec.ts Good test coverage for fn(). Tests for mockRestore, mockReturnValue/mockResolvedValue/mockRejectedValue after restore, serialization, and cross-mock invocation order are all present.

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    subgraph Electron["Electron Service"]
        EM[electron.mock / mockAll] --> MF[mockFactory.ts buildMockMethods]
        MF --> CDP[CDP bridge browser.electron.execute]
        CDP --> IM_E[Inner Mock native-spy fn]
        MF --> OM_E[Outer Mock native-spy fn]
    end
    subgraph Tauri["Tauri Service"]
        TM[tauri.mock] --> CM[createMock tauri mock.ts]
        CM --> TE[tauriExecute browser.execute]
        TE --> WM[window.__wdio_mocks__ native-spy fn]
        CM --> OM_T[Outer Mock native-spy fn]
    end
    subgraph TauriPlugin["Tauri Plugin guest-js"]
        INIT[init] --> II[setupInvokeInterception Wraps core.invoke]
        II --> WM
        INIT --> SPY[window.__wdio_spy__ native-spy]
        SPY --> WM
    end
    subgraph NativeSpy["@wdio/native-spy"]
        FN[fn] --> DISPATCH{Dispatch}
        DISPATCH -->|queue| IQ[implementationQueue]
        DISPATCH -->|rejected| DRJ[defaultRejectedValue]
        DISPATCH -->|impl| IFN[implementationFn]
        DISPATCH -->|resolved| DRS[defaultResolvedValue]
        DISPATCH -->|this| RT[returnThis]
        DISPATCH -->|return| DRV[defaultReturnValue]
        DISPATCH -->|restored| OF[originalFn]
    end
    IM_E --> FN
    WM --> FN
    OM_E --> FN
    OM_T --> FN
Loading

Fix All in Claude Code Fix All in Cursor

Reviews (13): Last reviewed commit: "fix(tauri): clear stale mocks at session..." | Re-trigger Greptile

Comment thread packages/native-spy/test/spy.spec.ts
…ck function

- Introduced a new test case to verify that the mock function returns the initial implementation passed to it.
- This enhances the testing coverage for the `getMockImplementation` method, ensuring it behaves as expected.
@goosewobbler goosewobbler removed scope:shared Shared utilities and infrastructure bump:patch Release a patch version labels Apr 20, 2026
…lectron and tauri environments

- Added exclusion for window and deeplink tests in electron configuration.
- Updated tauri configurations to maintain exclusion of window and deeplink tests, removing mocking tests from the exclusion list.
- Ensured consistency across test specifications for improved test execution.
…support

- Added `FnOptions` interface to allow passing an original function to the mock.
- Updated the `fn` function to call the original function if provided, improving mock behavior.
- Adjusted mock restoration to revert to the original function when available.
- Improved the `restoreElectronFunctionality` method to handle mock restoration more robustly, including fallback to original functions stored in `globalThis.originalApi`.
- Updated the `createMock` function to capture and store original functions for better restoration capabilities.
- Enhanced logging to provide detailed results of the restoration process, aiding in debugging and verification.
- Enhanced the `fn` function to better handle mock restoration and state tracking.
- Introduced a `mockRestored` flag to manage the restoration state of mocks.
- Updated the implementation logic to ensure correct handling of resolved and rejected values.
- Cleared implementation queue during mock resets to prevent unintended behavior.
…ion handling

- Added debug logging to track calls to inner mock functions, improving traceability during testing.
- Refined the implementation logic in `createMock` to ensure proper handling of function implementations, enhancing mock behavior.
…l tracking

- Updated the `fn` function to include a non-enumerable `lastCall` property on the state, allowing for better tracking of the most recent call arguments.
- Added a `lastCall` property to the mock function, making it enumerable for easier access.
- Refined comments for clarity and alignment with vitest's approach to state management.
…ll tracking

- Introduced a computed `lastCall` property on the mock function, providing convenient access to the most recent call made.
- Enhanced the mock's state management capabilities, aligning with previous improvements in tracking and logging.
… and update mocking tests

- Introduced a `restoreMocks` property in the Electron capabilities configuration to enable automatic restoration of mocks.
- Updated the mocking tests to remove clipboard state management, ensuring that mocks are restored to their original state after execution.
…rove call tracking

- Simplified the `restoreElectronFunctionality` method to enhance clarity and efficiency in restoring mocks.
- Updated the fallback restoration logic to ensure consistent behavior and improved return values.
- Refined the `createMock` function to enhance call tracking and logging, ensuring better traceability during testing.
Comment thread packages/native-spy/src/mock.ts
@goosewobbler goosewobbler added bump:patch Release a patch version and removed bump:patch Release a patch version labels Apr 21, 2026
…unctions

- Eliminated unnecessary resetting of the implementation function in `mockReturnValueOnce` and `mockResolvedValueOnce`, streamlining the mock behavior.
- Improved clarity and efficiency in the mock function's state management.
…e2e fixture

- Added a new button to the Electron app's UI for triggering a dialog.
- Implemented an event listener to invoke the 'show-open-dialog' API when the button is clicked, enhancing user interaction.
…nd mockRejectedValue after mockRestore

- Added new test cases to verify that mockReturnValue, mockResolvedValue, and mockRejectedValue can be called after mockRestore, ensuring correct behavior of mock functions.
- Enhanced test coverage for the native-spy package by validating the restoration and reconfiguration of mock functions.
- Updated the mock function to ensure that the `defaultReturnValue` is correctly returned when defined, improving the accuracy of mock behavior.
- Removed redundant code that previously handled `defaultReturnValue`, streamlining the logic for returning values in mock functions.
…from mockRestore

- Eliminated the call to restoreElectronFunctionality in the mockRestore method, simplifying the mock restoration process.
- Updated import statements to reflect the removal of unused functionality, enhancing code clarity.
@goosewobbler goosewobbler changed the title feat: address Electron mocking failures feat: address mocking failures Apr 21, 2026
- Improved the Tauri mocking implementation by simplifying the mock call tracking and synchronization process.
- Updated the `isMockFunction` method to accept both command names and mock function objects, enhancing usability.
- Added automatic synchronization of mock calls after executing commands, ensuring accurate call tracking.
- Enhanced error handling for undefined responses in the execute function, allowing for better handling of edge cases.
- Introduced tests to validate the new synchronization behavior and the updated `isMockFunction` logic, improving overall test coverage.
Comment thread packages/electron-service/src/mockFactory.ts
…kFactory

- Simplified the logic in `mockRejectedValue` and `mockRejectedValueOnce` methods to handle Error instances more effectively.
- Enhanced type handling for both API and class method mocks, ensuring consistent behavior across different mock types.
- Improved error message propagation when rejecting promises, providing clearer context for error handling in tests.
- Removed complex proxy-based interception strategies for the invoke method, streamlining the setup process.
- Updated logging to reflect the fallback to mock routing via window.__wdio_mocks__ when defineProperty fails, improving clarity on interception status.
- Enhanced code readability by eliminating unnecessary fallback strategies while maintaining mock functionality.
@goosewobbler goosewobbler force-pushed the fix/getMockImplementation branch from 050b445 to c9a9fa8 Compare April 21, 2026 23:22
- Updated the return type of the `mockReturnThis` method in the TauriMockInstance interface to return `Promise<TauriMock>` instead of `Promise<unknown>`, improving type safety and clarity.
- Adjusted the implementation in the `createMock` function to ensure consistent return type handling, enhancing overall mock functionality.
…ment

- Temporarily reverted the mockClear function to synchronous behavior to prevent race conditions during state clearing in the createMock function.
- Ensured that outerMockClear is called immediately before outerMockReset, maintaining the integrity of mock state management.
…ned context

- Modified the `resetAllMocks` and `restoreAllMocks` functions to accept an optional `TauriServiceContext`, ensuring compatibility with undefined context scenarios.
- Adjusted the execution calls in both functions to replace `undefined` with an empty string when no command prefix is provided, improving consistency in mock handling.
- Updated related tests to reflect these changes, ensuring accurate expectations for the execution calls.
…pace

- Upgraded the cache restore action from v4 to v5 for improved performance and features.
- Removed unnecessary whitespace in the script for better readability and consistency.
- Updated the mocha timeout setting from 60 seconds to 120 seconds to accommodate longer-running tests, enhancing overall test reliability.
- Removed the clipboard write operation from the beforeEach hook to ensure mocks are restored before any clipboard interactions.
- Moved the clipboard write operation to after the restoreAllMocks call, clarifying the test flow and ensuring accurate mock state during execution.
- Set maxInstances to 1 for embedded mode tests to ensure that the shared Tauri app instance is properly managed.
- Added comments to clarify the need for sequential execution due to global shared state across workers, preventing potential conflicts during test runs.
…bugging

- Upgraded the vscode-server-action from v1.3.0 to v1.4.0 across multiple workflow files to enhance debugging capabilities during test failures.
- Ensured consistent timeout settings for the debugging sessions in the respective workflows.
- Replaced the manual title retrieval and expectation with a more concise matcher using `toHaveTitle`, improving readability and maintainability of the test code.
- Ensured that the test still accurately verifies the application window title for the Electron E2E test app.
@goosewobbler goosewobbler force-pushed the fix/getMockImplementation branch from 04d73b2 to 5749adb Compare April 22, 2026 10:57
- Updated the cache save action from v4 to v5 to leverage improved features and performance.
- Ensured compatibility with the latest caching mechanisms in the workflow configuration.
- Updated `mockRejectedValue` and `mockRejectedValueOnce` to differentiate between `Error` instances and other values, ensuring that error messages are properly passed when an `Error` is rejected.
- Improved type handling in the mock functions to enhance clarity and maintainability of the code.
- Added new test cases to verify that `mockRejectedValue` and `mockRejectedValueOnce` correctly preserve error messages when rejecting with `Error` objects.
- Ensured that the error messages are accurately returned in the execution context, improving the robustness of error handling in the mocking framework.
…ebugging

- Updated the vscode-server-action from v1.4.0 to v1.5.0 across multiple workflow files to improve debugging capabilities during test failures.
- Ensured consistent timeout settings for the debugging sessions in the respective workflows.
…k methods

- Temporarily restored synchronous behavior for mockClear in both createClassMock and buildMockMethods to prevent race conditions with async operations.
- Updated comments for clarity on the purpose of these changes, enhancing maintainability and understanding of the code flow.
…ovider

- Implemented logic to reset `window.__wdio_mocks__` at the beginning of each session when using the embedded driver provider, ensuring a clean state for tests.
- Added tests to verify the clearing of stale mocks for embedded providers and confirm that non-embedded providers do not clear mocks.
- Enhanced error handling to gracefully manage failures during the clearing process.
@goosewobbler goosewobbler merged commit e122474 into main Apr 22, 2026
146 of 150 checks passed
@goosewobbler goosewobbler deleted the fix/getMockImplementation branch April 22, 2026 14:50
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bump:patch Release a patch version scope:spy

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant