Skip to content

refactor: rework how nock is setup and used to harden tests#395

Open
kamilogorek wants to merge 4 commits into
openfga:mainfrom
kamilogorek:cleanup-tests
Open

refactor: rework how nock is setup and used to harden tests#395
kamilogorek wants to merge 4 commits into
openfga:mainfrom
kamilogorek:cleanup-tests

Conversation

@kamilogorek
Copy link
Copy Markdown
Contributor

@kamilogorek kamilogorek commented May 3, 2026

This PR hardens everything around nock usage for network-based tests.

  • setup global assertions for pending nock requests
  • stop using manual scope assertions
  • cleanup network setup
  • remove duplicated mocks setup/cleanup

NOTE: will rebase once #394 is merged

Summary by CodeRabbit

  • Tests
    • Refactored test infrastructure to streamline HTTP mock lifecycle and assertion patterns across test suites.
    • Simplified global test setup utilities and per-test cleanup procedures for improved consistency.
    • Enhanced mock validation to better detect and report unmatched mocks during test execution.

Review Change Stack

@kamilogorek kamilogorek requested a review from a team as a code owner May 3, 2026 09:06
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 3, 2026

Important

Review skipped

Auto incremental reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: d9b365c2-475a-4853-b721-9690c6f313c7

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review

Walkthrough

Test infrastructure refactoring centralizes Nock mock lifecycle management by moving scope-tracking and cleanup logic into global setup, then simplifies all test assertions to rely on direct result checks instead of explicit mock-consumption verification.

Changes

Nock Mock Lifecycle Refactoring

Layer / File(s) Summary
Global Setup Infrastructure
tests/setup.ts
Adds OPENFGA_API_URL_HOST constant; updates beforeEach to selectively re-enable network for configured hosts; adds afterEach hook to clean pending mocks and throw if any remain.
API Executor Tests
tests/apiExecutor.test.ts
Reorganizes imports with type-only UserClientConfigurationParams; removes local beforeAll/afterEach/afterAll hooks from both main and path-parameters describe blocks.
Credentials Tests
tests/credentials.test.ts
Removes suite-level beforeEach/afterEach network-control hooks; replaces stored scope variables with inline nock() calls and removes scope.isDone() assertions in token endpoint normalization, PrivateKeyJWT, and concurrency/retry tests.
Headers Tests
tests/headers.test.ts
Removes global nock setup; moves test config into describe block; refactors all header assertion tests to use inline nock() interceptors without scope capture or isDone() checks.
Client Tests
tests/client.test.ts
Removes global afterEach cleanup hook; replaces scope.isDone() assertions with direct payload assertions across store, auth-model, write, check, batch-check, list-relations, and list-objects tests; adds selective nock.cleanAll() for negative-assertion cases.
Index Tests
tests/index.test.ts
Removes top-level nock.disableNetConnect(); replaces scope tracking and isDone() assertions with nocks.* helper setup and direct result assertions in token-exchange, retry, and SDK API-call tests; adds manual nock.cleanAll() where mocks are expected not to match.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Suggested reviewers

  • SoulPancake
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main refactoring effort: reorganizing nock setup and usage patterns across test files to improve test robustness.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

@kamilogorek kamilogorek changed the base branch from fix/default-retry-params to main May 4, 2026 09:09
SoulPancake
SoulPancake previously approved these changes May 11, 2026
@SoulPancake
Copy link
Copy Markdown
Member

@kamilogorek Do you mind resolving the conflicts in the test files in this one, Happy to take over otherwise :)

@kamilogorek
Copy link
Copy Markdown
Contributor Author

Rebased. All tests pass locally 🙇

Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

This PR refactors the test suite’s nock usage to make network-mocked tests more robust by centralizing setup/teardown and enforcing that all declared mocks are either consumed or explicitly cleaned up.

Changes:

  • Centralize nock configuration in tests/setup.ts and add a global afterEach assertion that fails tests when pending mocks remain.
  • Remove many per-test scope.isDone() assertions and repeated nock.cleanAll() hooks, relying on the global pending-mock assertion instead.
  • Simplify nock lifecycle handling in individual test files (e.g., removing custom restore/activate blocks).

Reviewed changes

Copilot reviewed 6 out of 6 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
tests/setup.ts Adds global nock net-connect configuration and a pending-mock assertion/cleanup in afterEach.
tests/index.test.ts Removes manual scope assertions/cleanup and relies on global pending-mock checks (with a few explicit cleanups where mocks must remain unused).
tests/headers.test.ts Removes per-test nock cleanup and scope.isDone() assertions in favor of global enforcement.
tests/credentials.test.ts Drops local nock setup/teardown and scope.isDone() assertions, relying on the centralized setup.
tests/client.test.ts Removes repeated nock.cleanAll() hooks and manual scope assertions; adds targeted cleanup where tests intentionally leave mocks unused.
tests/apiExecutor.test.ts Removes custom nock lifecycle management and aligns imports/types with the updated test approach.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread tests/setup.ts
Comment thread tests/index.test.ts
Copy link
Copy Markdown

@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

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@tests/setup.ts`:
- Line 10: The nock.allow rule currently uses startsWith with
nock.enableNetConnect which allows spoofed hostnames; change the check in the
nock.enableNetConnect callback (the function passed to nock.enableNetConnect) to
compare the exact hostname portion against OPENFGA_API_URL_HOST (for example by
extracting host.split(':')[0] or otherwise parsing hostname) so only an exact
match to OPENFGA_API_URL_HOST is allowed rather than startsWith.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: dca92d14-a484-49b9-831e-c16c2cc59df0

📥 Commits

Reviewing files that changed from the base of the PR and between 1ca65d8 and c4c9c23.

📒 Files selected for processing (6)
  • tests/apiExecutor.test.ts
  • tests/client.test.ts
  • tests/credentials.test.ts
  • tests/headers.test.ts
  • tests/index.test.ts
  • tests/setup.ts

Comment thread tests/setup.ts
Copy link
Copy Markdown
Member

@SoulPancake SoulPancake left a comment

Choose a reason for hiding this comment

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

I guess this this re-introduces a strange issue we had with nocks that fails only in CI but passes locally, need to investigate
#312

@kamilogorek
Copy link
Copy Markdown
Contributor Author

Should be good now. Not sure why nock's interception is behaving different way locally vs in CI 🤔

@codecov-commenter
Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 85.74%. Comparing base (1ca65d8) to head (2b3126f).

Additional details and impacted files
@@           Coverage Diff           @@
##             main     #395   +/-   ##
=======================================
  Coverage   85.74%   85.74%           
=======================================
  Files          25       25           
  Lines        1305     1305           
  Branches      265      265           
=======================================
  Hits         1119     1119           
  Misses        108      108           
  Partials       78       78           

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Copy link
Copy Markdown
Member

@SoulPancake SoulPancake left a comment

Choose a reason for hiding this comment

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

LGTM

@SoulPancake SoulPancake requested a review from rhamzeh May 12, 2026 13:29
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.

4 participants