Skip to content

Replace ava with vitest for frontend unit testing #8479

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 71 commits into from
Apr 17, 2025
Merged

Replace ava with vitest for frontend unit testing #8479

merged 71 commits into from
Apr 17, 2025

Conversation

hotzenklotz
Copy link
Member

@hotzenklotz hotzenklotz commented Mar 31, 2025

At the moment we have a a complicated and somewhat outdated stack for frontend testing:

  1. Convert all TS files to JS with esbuild
  • output is CommonJS modules for compatiblity with nodejs while the whole codebase already uses ES modules
  • import mocking with mockRequire is also commonJS and very confusing
  1. Run all unit tests in nodejs with ava framework

This workflow for testing TS, ESM and React code in node is configured very differently from the regular browser builds and is not very well supported out-of-the-box by either ava or the other tools.

vitest is very modern, works out-of-the-box with our current frontend setup without any additional configs. n this PR I migrated the frontend unit tests to vitest in an effort to rid ourselves of ava and many esbuild configs.

URL of deployed dev instance (used for testing):

  • https://___.webknossos.xyz

Steps to test:

  • CI tests should be enough

TODOs:

  • Update all remaining unit tests

    • test/sagas
    • test/shaders
    • test/helpers
    • test/model
    • test/schemas
    • test/api
    • test/libs
    • test/geometries
    • test/controller
    • test/misc
    • test/reducers
    • Helpers:
      • test/snapshots
      • test/fixtures
  • Follow up issue: Convert all e2e tests to vitest

    • test/puppeteer
    • test/screenshots
    • test/backend-snapshot-tests
    • test/screenshots-wkorg

Issues:


(Please delete unneeded items, merge only when none are left open)

Copy link
Contributor

coderabbitai bot commented Mar 31, 2025

📝 Walkthrough

Walkthrough

This update migrates the frontend test suite from the AVA testing framework to Vitest, affecting numerous test files across the codebase. The migration replaces AVA-specific imports, test constructs, and assertion styles with Vitest equivalents. Mocking strategies are updated to utilize Vitest's mocking utilities (vi.mock, vi.fn), and global mocks are centralized. Helper functions and test context interfaces are refactored for improved type safety and modularity. Additionally, Node.js version requirements are updated to 22, and related documentation and CI workflows are revised accordingly. Minor adjustments include making a method parameter optional and removing some warning logs. No production code logic is altered beyond these minor API and test helper changes.

Changes

Files/Areas Change Summary
.github/workflows/build_test_deploy.yml, DEV_INSTALL.md, MIGRATIONS.unreleased.md Updated Node.js version to 22 in workflows and documentation; streamlined frontend lint and test commands; added frontend test coverage reporting in CI.
.github/Dockerfile.webknossos Updated Node.js version argument from 18.x to 22.x for image builds.
frontend/javascripts/oxalis/api/api_latest.ts Made treeId parameter in TracingApi.setTreeName optional.
frontend/javascripts/oxalis/model/volumetracing/volume_annotation_sampling.ts Removed calls to warning logs for failed bucket creation in upsample and downsample functions.
frontend/javascripts/oxalis/workers/byte_array_lz4_compression.worker.ts Removed export of __compressLz4BlockHelper function; changed LZ4 import to local wrapper.
frontend/javascripts/oxalis/workers/byte_arrays_to_lz4_base64.worker.ts, slow_byte_array_lz4_compression.worker.ts Changed LZ4 import from "lz4-wasm" to local wrapper "./lz4_wasm_wrapper"; removed usage of helper function in slow compression worker; updated block comments.
frontend/javascripts/oxalis/workers/lz4_wasm_wrapper.ts Added new wrapper module re-exporting lz4-wasm to enable swapping with Node.js version during tests.
frontend/javascripts/libs/window.ts Removed a commented-out mock line; added trailing newline.
frontend/javascripts/test/_ava_polyfill_provider.ts Removed global polyfill for DOMException.
frontend/javascripts/test/global_mocks.ts Added a new centralized global mocks setup for frontend tests; mocked various utilities and global objects; exported a fixed TIMESTAMP constant.
frontend/javascripts/test/helpers/apiHelpers.ts Refactored and renamed test setup function for Vitest; replaced AVA, mock-require, and sinon mocks with Vitest mocks; introduced WebknossosTestContext interface for typed test context.
frontend/javascripts/test/helpers/run-async.ts Improved type annotations and added detailed JSDoc; added safety checks and consistent Promise wrapping for asynchronous function execution.
frontend/javascripts/test/helpers/sagaHelpers.ts Updated assertion functions to use Vitest's expect instead of AVA's test context; added JSDoc comments for clarity.
frontend/javascripts/test/helpers/saveHelpers.ts Simplified array type annotations in function signatures from verbose Array<...> to shorthand ...[].
frontend/javascripts/test/libs/transform_spec_helpers.ts Changed assertion handler from AVA's context to Vitest's expect; updated assertion style for vector component comparisons.
frontend/javascripts/test/mocks/updatable_texture.mock.ts Switched from mock-require to Vitest's vi.mock for mocking UpdatableTexture; renamed mock class accordingly.
frontend/javascripts/test/**/*.spec.ts, frontend/javascripts/test/**/*.mock.ts Migrated all test suites from AVA to Vitest: replaced test constructs, assertion styles, and mocks; grouped tests inside describe blocks; updated or removed legacy helper functions; improved typing and modularity; deleted obsolete AVA-specific mocks and replaced with Vitest equivalents.
frontend/javascripts/test/model/binary/layers/wkstore_adapter.mock.ts, reducers/save_reducer.mock.ts, skeletontracing_saga.mock.ts, frontend/javascripts/test/mocks/globals.mock.ts Deleted obsolete AVA/mock-require-based mock files.
frontend/javascripts/test/e2e-setup.ts, frontend/javascripts/test/puppeteer/*.ts Updated LZ4 mock import path; changed JSDOM import to ES module style with TypeScript ignore; removed global navigator mock.

Suggested labels

refactoring

Suggested reviewers

  • philippotto

Poem

🐇✨
A hop, a leap, from AVA to Vitest,
Our tests now run with fluffy zest!
Mocks are tidied, helpers shine,
Node 22—oh, how divine!
With grouped describes and cleaner code,
This bunny’s heart is in test mode.
Onward we bound, with coverage in sight,
Our frontend’s future is looking bright!

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@hotzenklotz
Copy link
Member Author

For the most part, only the following changes needed to be done:

  1. Replace Ava's test() with Vitest's it()
  2. Replace Ava's t.is() with Vitest's expect().toBe()
  3. Replace Ava's t.deepEqual() with Vitest's expect().toEqual()
  4. Replace Ava's t.true() with Vitest's expect().toBe(true)
  5. Replace mockRequire with vi.mock()
  6. Replace sinon.stub() with vi.spyOn()

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

🧹 Nitpick comments (2)
.github/workflows/build_test_deploy.yml (2)

44-48: Remove trailing spaces and consider cleaning up commented-out steps.

There are trailing spaces at line 44, flagged by YAMLlint. Also, consider removing or documenting the commented-out artifact download step if it's not planned for future use, to keep the workflow clean.

-      # - name: Download Coverage Artifacts 
-      #   uses: actions/download-artifact@v4
-      #   with:
-      #     name: vitest-coverage-master
-      #     path: coverage
+      # - name: Download Coverage Artifacts
+      #   uses: actions/download-artifact@v4
+      #   with:
+      #     name: vitest-coverage-master
+      #     path: coverage

[static_analysis]

🧰 Tools
🪛 YAMLlint (1.35.1)

[error] 44-44: trailing spaces

(trailing-spaces)


50-50: Fix excessive spaces after colon.

Line 50 has too many spaces after the colon, which is flagged by YAMLlint. Adjust to a single space for YAML style consistency.

-        uses:  davelosert/vitest-coverage-report-action@v2
+        uses: davelosert/vitest-coverage-report-action@v2

[static_analysis]

🧰 Tools
🪛 YAMLlint (1.35.1)

[warning] 50-50: too many spaces after colon

(colons)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between edb083f and 2e4540a.

📒 Files selected for processing (1)
  • .github/workflows/build_test_deploy.yml (4 hunks)
🧰 Additional context used
🪛 YAMLlint (1.35.1)
.github/workflows/build_test_deploy.yml

[error] 44-44: trailing spaces

(trailing-spaces)


[warning] 50-50: too many spaces after colon

(colons)

⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: build-smoketest-push
  • GitHub Check: backend-tests
🔇 Additional comments (3)
.github/workflows/build_test_deploy.yml (3)

31-31: Approve Node.js version update to 22.

Upgrading to Node.js 22 across all jobs is a forward-compatible move and aligns with the updated frontend tooling requirements.

Also applies to: 71-71, 130-130


43-43: Approve migration to Vitest and coverage enablement.

Switching the test command to use Vitest with coverage is correct and matches the new test suite setup.


49-59: Approve coverage reporting and artifact upload integration.

Integrating Vitest coverage reporting and conditional artifact upload is a best practice for CI visibility and aligns with the new test stack.

🧰 Tools
🪛 YAMLlint (1.35.1)

[warning] 50-50: too many spaces after colon

(colons)

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

🧹 Nitpick comments (2)
.github/workflows/build_test_deploy.yml (2)

44-48: Remove trailing spaces and commented-out artifact download step for cleanliness.

There are trailing spaces at line 44, and the commented-out artifact download step (lines 44-48) can be removed if not needed to keep the workflow clean and avoid linter warnings.

-      # - name: Download Coverage Artifacts 
-      #   uses: actions/download-artifact@v4
-      #   with:
-      #     name: vitest-coverage-master
-      #     path: coverage
🧰 Tools
🪛 YAMLlint (1.35.1)

[error] 44-44: trailing spaces

(trailing-spaces)


50-50: Fix excessive spaces after colon for YAML style compliance.

There are too many spaces after the colon on line 50. This is a minor YAML formatting issue flagged by static analysis.

-        uses:  davelosert/vitest-coverage-report-action@v2
+        uses: davelosert/vitest-coverage-report-action@v2
🧰 Tools
🪛 YAMLlint (1.35.1)

[warning] 50-50: too many spaces after colon

(colons)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2e4540a and ae7890e.

📒 Files selected for processing (6)
  • .github/workflows/build_test_deploy.yml (4 hunks)
  • frontend/javascripts/oxalis/workers/byte_array_lz4_compression.worker.ts (1 hunks)
  • frontend/javascripts/oxalis/workers/byte_arrays_to_lz4_base64.worker.ts (1 hunks)
  • frontend/javascripts/oxalis/workers/lz4_wasm_wrapper.ts (1 hunks)
  • frontend/javascripts/test/global_mocks.ts (1 hunks)
  • frontend/javascripts/test/model/binary/pullqueue.spec.ts (1 hunks)
✅ Files skipped from review due to trivial changes (3)
  • frontend/javascripts/oxalis/workers/byte_array_lz4_compression.worker.ts
  • frontend/javascripts/oxalis/workers/lz4_wasm_wrapper.ts
  • frontend/javascripts/oxalis/workers/byte_arrays_to_lz4_base64.worker.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • frontend/javascripts/test/global_mocks.ts
  • frontend/javascripts/test/model/binary/pullqueue.spec.ts
🧰 Additional context used
🪛 YAMLlint (1.35.1)
.github/workflows/build_test_deploy.yml

[error] 44-44: trailing spaces

(trailing-spaces)


[warning] 50-50: too many spaces after colon

(colons)

🔇 Additional comments (2)
.github/workflows/build_test_deploy.yml (2)

31-31: Node.js version bump to 22 is appropriate.

Upgrading to Node.js 22 aligns with the latest LTS and the requirements of modern tooling like Vitest. No issues found.

Also applies to: 71-71, 130-130


43-43: Frontend test command migration to Vitest is correct.

Switching to yarn run vitest run --coverage.enabled true is the right approach for Vitest-based test suites and enables coverage reporting.

@hotzenklotz hotzenklotz requested a review from philippotto April 16, 2025 13:34
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

🧹 Nitpick comments (1)
CHANGELOG.unreleased.md (1)

27-27: Minor grammar and spelling improvements for clarity.

Consider updating the entry to read: "Replace frontend unit testing framework ava with vitest. The minimum required Node.js version is now 22+." This adds the missing determiner and uses the official spelling of "Node.js".

Apply this diff for improved clarity:

- - Replace frontend unit testing framework `ava` with `vitest`. Minimum required nodejs version is now `22+`. [#8479](https://github.com/scalableminds/webknossos/pull/8479)
+ - Replace frontend unit testing framework `ava` with `vitest`. The minimum required Node.js version is now `22+`. [#8479](https://github.com/scalableminds/webknossos/pull/8479)
🧰 Tools
🪛 LanguageTool

[uncategorized] ~27-~27: A determiner appears to be missing. Consider inserting it.
Context: ... testing framework ava with vitest. Minimum required nodejs version is now 22+. [...

(AI_EN_LECTOR_MISSING_DETERMINER)


[uncategorized] ~27-~27: The official spelling of this programming framework is “Node.js”.
Context: ...k ava with vitest. Minimum required nodejs version is now 22+. [#8479](https://g...

(NODE_JS)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between cb287c9 and 81b38da.

📒 Files selected for processing (1)
  • CHANGELOG.unreleased.md (1 hunks)
🧰 Additional context used
🪛 LanguageTool
CHANGELOG.unreleased.md

[uncategorized] ~27-~27: A determiner appears to be missing. Consider inserting it.
Context: ... testing framework ava with vitest. Minimum required nodejs version is now 22+. [...

(AI_EN_LECTOR_MISSING_DETERMINER)


[uncategorized] ~27-~27: The official spelling of this programming framework is “Node.js”.
Context: ...k ava with vitest. Minimum required nodejs version is now 22+. [#8479](https://g...

(NODE_JS)

Copy link
Member

@philippotto philippotto left a comment

Choose a reason for hiding this comment

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

awesome! I'm not done with the review yet, but already submitting my few comments. will do the rest tomorrow.

Copy link
Member

@philippotto philippotto left a comment

Choose a reason for hiding this comment

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

really, really cool! I'm glad to see that mockRequie is gone now and the alternative looks much more pleasant.

I only left some minor clean up comments. will monkey-test afterwards.

};

// Mock common utility functions
// Mock modules instead of using mockRequire
Copy link
Member

Choose a reason for hiding this comment

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

let's not mention the you-know-who lib anymore ^^ shouldnt be relevant for future readers

Suggested change
// Mock modules instead of using mockRequire

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

🧹 Nitpick comments (4)
MIGRATIONS.unreleased.md (1)

11-11: Correct the official spelling of Node.js. The runtime should be referred to as “Node.js” (with a lowercase “j” and a period), not “NodeJs.”

🧰 Tools
🪛 LanguageTool

[uncategorized] ~11-~11: The official spelling of this programming framework is “Node.js”.
Context: ...m//pull/8460) - NodeJs version 22+ is required. [#8479](http...

(NODE_JS)

frontend/javascripts/test/helpers/apiHelpers.ts (3)

74-103: Consider adding JSDoc comments to mock implementation functions

The implementation of receiveJSONMockImplementation is clear but would benefit from JSDoc comments explaining what fixtures are expected and the overall purpose of this helper function.

+/**
+ * Mock implementation for Request.receiveJSON
+ * Returns fixture data based on URL patterns and annotation type
+ * @param url The request URL
+ * @param options Request options
+ * @param annotationFixture The fixture data to use for annotation responses
+ * @returns Promise resolving to mock data
+ */
function receiveJSONMockImplementation(
  url: string,
  options: any,
  annotationFixture: typeof SKELETON_ANNOTATION | typeof VOLUME_ANNOTATION | typeof TASK_ANNOTATION,
) {

105-110: Consider typing the options parameter

The _options parameter in sendJSONReceiveJSONMockImplementation is marked with an underscore but typed as any. Consider creating a proper interface for this parameter or removing the underscore if the parameter is intentionally not used.

-function sendJSONReceiveJSONMockImplementation(url: string, _options?: any) {
+function sendJSONReceiveJSONMockImplementation(url: string, options?: RequestOptions) {

Where RequestOptions would be a proper interface defined for this purpose.


222-223: Consider updating the error throwing pattern

The current error handling creates a new Error with the message from the caught error, but ignores the stack trace from the original error.

-    // @ts-ignore
-    throw new Error(error.message);
+    // Preserve the original error stack if possible
+    if (error instanceof Error) {
+      throw error;
+    } else {
+      throw new Error(String(error));
+    }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 81b38da and d8b9ade.

📒 Files selected for processing (4)
  • MIGRATIONS.unreleased.md (1 hunks)
  • frontend/javascripts/test/global_mocks.ts (1 hunks)
  • frontend/javascripts/test/helpers/apiHelpers.ts (4 hunks)
  • frontend/javascripts/test/model/cuckoo_table_uint64.spec.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • frontend/javascripts/test/global_mocks.ts
  • frontend/javascripts/test/model/cuckoo_table_uint64.spec.ts
🧰 Additional context used
🪛 LanguageTool
MIGRATIONS.unreleased.md

[uncategorized] ~11-~11: The official spelling of this programming framework is “Node.js”.
Context: ...m//pull/8460) - NodeJs version 22+ is required. [#8479](http...

(NODE_JS)

⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: frontend-tests
  • GitHub Check: backend-tests
  • GitHub Check: build-smoketest-push
🔇 Additional comments (6)
frontend/javascripts/test/helpers/apiHelpers.ts (6)

1-1: Great modernization of imports for Vitest migration

The imports have been properly updated to use Vitest types and testing utilities instead of the previous AVA/sinon setup. The explicit import of ModelType as type helps maintain type safety.

Also applies to: 25-36


45-54: Well-structured test context interface

The creation of the WebknossosTestContext interface extending the Vitest base context is a good practice. It provides strong typing for the test environment and makes the API contract between the test setup and test cases clear and maintainable.


56-68: Good implementation of Vitest mocking pattern

The migration from manual mocks to using Vitest's vi.mock() API is well-implemented. This centralizes the mocking logic and makes it more maintainable compared to the previous approach.


179-188: Well-structured test context population

Good job setting up the test context with all necessary components. The tearDownPullQueues helper is particularly useful for cleaning up resources between tests.


193-198: Good use of vi.mocked type assertion

Using vi.mocked() to properly type the mocked functions is a good practice that ensures type safety when setting mock implementations.


206-225: Improved error handling with try/catch

The migration to async/await with proper try/catch handling is a significant improvement over the previous promise chain approach. The error reporting is clear and will make test failures easier to diagnose.

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

🧹 Nitpick comments (1)
frontend/javascripts/test/helpers/apiHelpers.ts (1)

220-228: Simplify error handling

The error handling logic can be simplified to avoid the ts-ignore and improve readability.

  } catch (error) {
    console.error("model.fetch() failed", error);
-    if (error instanceof Error) {
-      throw error;
-    } else {
-      // @ts-ignore
-      throw new Error(error.message);
-    }
+    // Re-throw as Error with appropriate message
+    throw error instanceof Error ? error : new Error(String(error));
  }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0594b65 and 608942c.

📒 Files selected for processing (1)
  • frontend/javascripts/test/helpers/apiHelpers.ts (4 hunks)
🧰 Additional context used
🪛 GitHub Check: frontend-tests
frontend/javascripts/test/helpers/apiHelpers.ts

[failure] 194-194:
Argument of type 'RequestOptions | undefined' is not assignable to parameter of type 'RequestOptions'.

⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: build-smoketest-push
  • GitHub Check: backend-tests
🔇 Additional comments (4)
frontend/javascripts/test/helpers/apiHelpers.ts (4)

1-39: Clean migration from ava to vitest

The imports have been successfully updated to use Vitest instead of ava for testing. The additional imports properly support the new asynchronous testing approach.


45-54: Well-structured test context interface

The new WebknossosTestContext interface is well-designed, extending Vitest's BaseTestContext with proper typing for model, mocks, API, and helper functions. This provides good type safety for tests.


56-144: Effective Vitest mocking implementation

The refactored mock implementations using Vitest's vi.mock() and related utilities are correctly implemented. The mock implementations for Request and other modules provide appropriate test responses based on URL patterns.


169-188: Improved setup function with async/await

The renamed setup function with async/await pattern and proper test context initialization is a significant improvement over the previous implementation. Good job structuring the test context properties.

@hotzenklotz
Copy link
Member Author

@philippotto Thanks for all the feedback. I addressed all of it. Ready to rumble.

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

♻️ Duplicate comments (1)
frontend/javascripts/test/helpers/apiHelpers.ts (1)

193-195: ⚠️ Potential issue

Fix type error with RequestOptions parameter

The options parameter is passed directly to receiveJSONMockImplementation without checking if it's undefined, but the function expects a non-optional RequestOptions object.

vi.mocked(Request).receiveJSON.mockImplementation((url, options) =>
-  receiveJSONMockImplementation(url, options, annotationFixture),
+  receiveJSONMockImplementation(url, options || {}, annotationFixture),
);
🧹 Nitpick comments (1)
frontend/javascripts/test/helpers/apiHelpers.ts (1)

220-228: Improve error handling type safety

The error handling uses @ts-ignore to work around a TypeScript error. It would be better to use a more type-safe approach to handle unknown error types.

try {
  // ...existing code...
} catch (error) {
  console.error("model.fetch() failed", error);
-  if (error instanceof Error) {
+  // Handle all error types in a type-safe way
+  const errorMessage = error instanceof Error ? error.message : String(error);
+  throw new Error(`Failed to set up Webknossos for testing: ${errorMessage}`);
-  } else {
-    // @ts-ignore
-    throw new Error(error.message);
-  }
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 608942c and ebb5ab5.

📒 Files selected for processing (1)
  • frontend/javascripts/test/helpers/apiHelpers.ts (4 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
frontend/javascripts/test/helpers/apiHelpers.ts (9)
frontend/javascripts/oxalis/model.ts (1)
  • ModelType (370-370)
frontend/javascripts/oxalis/api/api_latest.ts (1)
  • ApiInterface (2823-2828)
frontend/javascripts/libs/request.ts (1)
  • RequestOptions (32-32)
frontend/javascripts/oxalis/model/actions/organization_actions.ts (1)
  • setActiveOrganizationAction (8-12)
frontend/javascripts/oxalis/workers/slow_byte_array_lz4_compression.worker.ts (1)
  • setSlowCompression (10-12)
frontend/javascripts/oxalis/model/helpers/proto_helpers.ts (2)
  • parseProtoTracing (23-38)
  • parseProtoAnnotation (72-82)
frontend/javascripts/oxalis/controller/scene_controller_provider.ts (1)
  • setSceneController (16-18)
tools/proxy/proxy.js (1)
  • app (11-11)
frontend/javascripts/oxalis/api/wk_dev.ts (1)
  • api (62-68)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: build-smoketest-push
  • GitHub Check: backend-tests
  • GitHub Check: frontend-tests
🔇 Additional comments (5)
frontend/javascripts/test/helpers/apiHelpers.ts (5)

46-54: Well-structured test context interface

The WebknossosTestContext interface is well-defined and provides clear typing for the test environment. This improves type safety and makes the test helpers more maintainable.


57-68: Clean and consistent mocking approach

The switch to Vitest's mocking facilities is clean and consistent. Using vi.mock() with specific mock implementations makes the test setup more explicit and easier to understand.


169-173: Improved function signature with async/await

The function signature has been improved by:

  1. Using a more descriptive name (setupWebknossosForTesting)
  2. Accepting a typed testContext parameter
  3. Using async/await for better readability and error handling

184-188: Good implementation of tearDownPullQueues helper

The tearDownPullQueues helper is a good addition that ensures tests clean up resources properly. This prevents test pollution and improves test isolation.


76-76: Good use of default parameter value

Using a default empty object for the options parameter is a good practice to handle optional parameters safely.

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

🧹 Nitpick comments (1)
frontend/javascripts/test/helpers/apiHelpers.ts (1)

206-228: Well-implemented async error handling

The try-catch block with proper error logging and type checking for the Error instance follows best practices for async error handling in TypeScript.

However, consider simplifying the error re-throwing logic:

  catch (error) {
    console.error("model.fetch() failed", error);
-   if (error instanceof Error) {
-     throw error;
-   } else {
-     // @ts-ignore
-     throw new Error(error.message);
-   }
+   // Re-throw as is if it's already an Error, otherwise wrap it
+   throw error instanceof Error ? error : new Error(String(error));
  }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ebb5ab5 and 1e34e88.

📒 Files selected for processing (1)
  • frontend/javascripts/test/helpers/apiHelpers.ts (4 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
frontend/javascripts/test/helpers/apiHelpers.ts (7)
frontend/javascripts/oxalis/model.ts (1)
  • ModelType (370-370)
frontend/javascripts/oxalis/api/api_latest.ts (1)
  • ApiInterface (2823-2828)
frontend/javascripts/libs/request.ts (1)
  • RequestOptions (32-32)
frontend/javascripts/oxalis/model/actions/organization_actions.ts (1)
  • setActiveOrganizationAction (8-12)
frontend/javascripts/oxalis/workers/slow_byte_array_lz4_compression.worker.ts (1)
  • setSlowCompression (10-12)
frontend/javascripts/oxalis/model/helpers/proto_helpers.ts (2)
  • parseProtoTracing (23-38)
  • parseProtoAnnotation (72-82)
frontend/javascripts/oxalis/controller/scene_controller_provider.ts (1)
  • setSceneController (16-18)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: build-smoketest-push
  • GitHub Check: frontend-tests
  • GitHub Check: backend-tests
🔇 Additional comments (10)
frontend/javascripts/test/helpers/apiHelpers.ts (10)

1-1: Good migration to Vitest testing framework

The import of Vitest's testing utilities and TestContext is appropriate for the migration from AVA.


25-25: Fixed import syntax for ModelType

The import syntax correctly uses a named import { ModelType } which matches the type export in oxalis/model.ts.


27-40: Well-organized imports for test setup

The imports are logically organized to support the test environment setup, including workers, models, and API interfaces needed for the testing functionality.


45-54: Good type safety with WebknossosTestContext interface

The extended test context interface improves type safety and provides better IDE support by explicitly defining the shape of the test context object.


56-72: Improved mocking approach with Vitest

Using Vitest's vi.mock() API for mocking modules is cleaner and more maintainable than the previous approach. This centralizes the mocking configuration and makes the testing setup more consistent.


74-77: Good fix for RequestOptions parameter

Making the options parameter optional with a default empty object value fixes the type error identified in previous reviews.


112-122: Nicely implemented partial module mocking

The approach to import the original module and then override specific functions is a good pattern for partial mocking, preserving the original behavior for most of the module while only mocking what's needed for testing.


169-173: Improved function signature for setupWebknossosForTesting

The renamed function with async/await signature and strongly typed parameters is more descriptive and provides better TypeScript support.


179-188: Well-structured test context initialization

The initialization of the test context with model, mocks, and helper functions provides a clean API for tests to interact with the application.


197-198: Good use of lodash's cloneDeep for fixtures

Using _.cloneDeep() ensures that each test gets fresh copies of the fixture data, preventing test interdependencies that could lead to flaky tests.

Copy link
Member

@philippotto philippotto left a comment

Choose a reason for hiding this comment

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

Awesome!!! nicer code, easier to use and it's faster too (24 seconds / 22% faster when compared to another ci run).

thank you for tackling this issue!

@hotzenklotz
Copy link
Member Author

With regards to speed: AFAIK, ava executed even individual test in parallel. vitest executes only test suites in parallel and all tests within one suite are run in sequentially. I think this behavior is fine, but there might even be more gains to be had.

@hotzenklotz hotzenklotz merged commit 7d25fa5 into master Apr 17, 2025
5 checks passed
@hotzenklotz hotzenklotz deleted the vitest branch April 17, 2025 09:16
@philippotto
Copy link
Member

With regards to speed: AFAIK, ava executed even individual test in parallel. vitest executes only test suites in parallel and all tests within one suite are run in sequentially. I think this behavior is fine, but there might even be more gains to be had.

I tested this a bit last week with the sharding-feature of vitest. the feature allows to split all specs (within all files) into several shards and then run a vitest process for each shard. I did not notice any speed up (for some shard counts it got even worse). so, I assume that the tests are already cpu-bound. this was also the reason why I split the one big volume-related test suite into two.
but yes, more gains are probably still possible somehow.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants