Skip to content

[No QA] Remove unsafe type assertions from DomainSelectorsTest.ts tests#96518

Merged
blimpich merged 3 commits into
Expensify:mainfrom
KJ21-ENG:sbf/cli-19687d08-3353-445b-8137-4dcdb19a4279-94739-domainselectorstest.ts
Jul 23, 2026
Merged

[No QA] Remove unsafe type assertions from DomainSelectorsTest.ts tests#96518
blimpich merged 3 commits into
Expensify:mainfrom
KJ21-ENG:sbf/cli-19687d08-3353-445b-8137-4dcdb19a4279-94739-domainselectorstest.ts

Conversation

@KJ21-ENG

Copy link
Copy Markdown
Contributor

Explanation of Change

Removed @typescript-eslint/no-unsafe-type-assertion violations from tests/unit/DomainSelectorsTest.ts as part of the cleanup for Expensify/App issue #94739.

What changed:

  • Replaced unsafe Domain selector test assertions with typed local fixture builders.
  • Separated model-conforming overrides from explicit malformed backend boundary shapes.
  • Preserved missing-settings, absent-key, pending-action, and security-group scenario semantics.

Why this approach is safe:

  • The change is limited to the existing Domain selector unit test file.
  • All 88 existing scenarios pass and the protected test and assertion inventory is preserved.
  • Focused lint, formatter, compiler, diff, and trusted Fork CI checks passed.

Reviewer focus:

  1. Confirm Partial model overrides remain type checked while explicit boundary values stay narrowly bounded.
  2. Confirm missing properties are deleted at runtime where the original tests exercised key absence.
  3. Confirm no selector or production behavior changes are included.

Safety checks:

  • Target-rule count reduced from 56 to 0.
  • Focused DomainSelectorsTest suite passed all 88 tests.
  • Three independent reviewers and the evaluator cleared the exact revision.
  • Trusted Fork CI passed for the signed commit.

Fixed Issues

$ #94739
PROPOSAL: #94739 (comment)

Count change

Current baseline source:

  • config/eslint/eslint.seatbelt.tsv

Before:

  • tests/unit/DomainSelectorsTest.ts: 56 violations

After:

  • tests/unit/DomainSelectorsTest.ts: 0 violations

Net reduction:

  • 56 fewer @typescript-eslint/no-unsafe-type-assertion violations.

TSV evidence:

  • Writable lint removed the target row when the count reached zero, or updated it to the exact remaining count.
  • The generated TSV was restored byte-for-byte and is intentionally not included in this PR because Expensify/App post-merge automation tightens the baseline on main.

Tests

  1. Run:

    npm run lint -- --show-warnings tests/unit/DomainSelectorsTest.ts
    

    Verify focused lint passes with no target-rule warnings for the edited file.

  2. Run:

    CI=true npm run lint -- --no-cache --show-warnings tests/unit/DomainSelectorsTest.ts
    

    Verify the generated seatbelt row reflects 0 violations, then restore config/eslint/eslint.seatbelt.tsv before committing.

  3. Run:

    npm run test -- tests/unit/DomainSelectorsTest.ts
    

    Verify the focused test suite passes.

  4. Verification result: Focused lint, CI lint and TSV generation, all 88 DomainSelectorsTest cases, formatting, React Compiler, diff hygiene, and trusted Fork CI passed.

Offline tests

Not applicable: this test-only fixture refactor does not change offline application behavior.

QA Steps

Run the focused lint and DomainSelectorsTest commands above. No staging or production QA is required because application runtime behavior is unchanged.

PR Author Checklist

  • I linked the correct issue in the ### Fixed Issues section above
  • I wrote clear testing steps that cover the changes made in this PR
    • I added steps for local testing in the Tests section
    • I added steps for the expected offline behavior in the Offline steps section
    • I added steps for Staging and/or Production testing in the QA steps section
    • I added steps to cover failure scenarios (i.e. verify an input displays the correct error message if the entered data is not correct)
    • I turned off my network connection and tested it while offline to ensure it matches the expected behavior (i.e. verify the default avatar icon is displayed if app is offline)
    • I tested this PR with a High Traffic account against the staging or production API to ensure there are no regressions (e.g. long loading states that impact usability).
  • I included screenshots or videos for tests on all platforms
  • I ran the tests on all platforms & verified they passed on:
    • Android: Native
    • Android: mWeb Chrome
    • iOS: Native
    • iOS: mWeb Safari
    • MacOS: Chrome / Safari
  • I verified there are no console errors (if there's a console error not related to the PR, report it or open an issue for it to be fixed)
  • I followed proper code patterns (see Reviewing the code)
    • I verified that comments were added to code that is not self explanatory
    • I verified that any new or modified comments were clear, correct English, and explained "why" the code was doing something instead of only explaining "what" the code was doing.
    • I verified any copy / text that was added to the app is grammatically correct in English. It adheres to proper capitalization guidelines (note: only the first word of header/labels should be capitalized), and is either coming verbatim from figma or has been approved by marketing (in order to get marketing approval, ask the Bug Zero team member to add the Waiting for copy label to the issue)
  • If a new code pattern is added I verified it was agreed to be used by multiple Expensify engineers
  • I followed the guidelines as stated in the Review Guidelines
  • I tested other components that can be impacted by my changes (i.e. if the PR modifies a shared library or component like Avatar, I verified the components using Avatar are working as expected)
  • If a new CSS style is added I verified that:
    • A similar style doesn't already exist
    • The style can't be created with an existing StyleUtils function (i.e. StyleUtils.getBackgroundAndBorderStyle(theme.componentBG))
  • If new assets were added or existing ones were modified, I verified that:
    • The assets are optimized and compressed (for SVG files, run npm run compress-svg)
    • The assets load correctly across all supported platforms.
  • If the PR modifies code that runs when editing or sending messages, I tested and verified there is no unexpected behavior for all supported markdown - URLs, single line code, code blocks, quotes, headings, bold, strikethrough, and italic.
  • If the PR modifies a generic component, I tested and verified that those changes do not break usages of that component in the rest of the App (i.e. if a shared library or component like Avatar is modified, I verified that Avatar is working as expected in all cases)
  • If the PR modifies a component related to any of the existing Storybook stories, I tested and verified all stories for that component are still working as expected.
  • If the PR modifies a component or page that can be accessed by a direct deeplink, I verified that the code functions as expected when the deeplink is used - from a logged in and logged out account.
  • If the PR modifies the UI (e.g. new buttons, new UI components, changing the padding/spacing/sizing, moving components, etc) or modifies the form input styles:
    • I verified that all the inputs inside a form are aligned with each other.
    • I added Design label and/or tagged @Expensify/design so the design team can review the changes.
  • I added unit tests for any new feature or bug fix in this PR to help automatically prevent regressions in this user flow.
  • If the main branch was merged into this PR after a review, I tested again and verified the outcome was still expected according to the Test steps.

Screenshots/Videos

Android: Native

Not applicable: this test-only change does not modify runtime behavior on any platform.

Screenshots and videos are not applicable because there are no user-visible changes.

Android: mWeb Chrome

Not applicable: this test-only change does not modify runtime behavior on any platform.

Screenshots and videos are not applicable because there are no user-visible changes.

iOS: Native

Not applicable: this test-only change does not modify runtime behavior on any platform.

Screenshots and videos are not applicable because there are no user-visible changes.

iOS: mWeb Safari

Not applicable: this test-only change does not modify runtime behavior on any platform.

Screenshots and videos are not applicable because there are no user-visible changes.

MacOS: Chrome / Safari

Not applicable: this test-only change does not modify runtime behavior on any platform.

Screenshots and videos are not applicable because there are no user-visible changes.

@KJ21-ENG
KJ21-ENG marked this pull request as ready for review July 20, 2026 19:53
@KJ21-ENG
KJ21-ENG requested a review from a team as a code owner July 20, 2026 19:53
@melvin-bot
melvin-bot Bot requested a review from blimpich July 20, 2026 19:53
@melvin-bot

melvin-bot Bot commented Jul 20, 2026

Copy link
Copy Markdown

@blimpich Please copy/paste the Reviewer Checklist from here into a new comment on this PR and complete it. If you have the K2 extension, you can simply click: [this button]

@melvin-bot
melvin-bot Bot removed the request for review from a team July 20, 2026 19:53
Comment thread tests/unit/DomainSelectorsTest.ts Outdated
shared: {},
};

type DomainBoundarySecurityGroup = {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

These two test-local types shadow production and don't earn their place.

DomainBoundarySecurityGroup is a hand-loosened copy of DomainSecurityGroup (src/types/onyx/Domain.ts:104, whose shared is Record<string, 'read' | null>). DomainBoundaryValue is a ≈unknown union. Both only type boundaryEntries, and every value there flows through Reflect.set(fixture, key, value)value: any, so the static type is erased at the write and never asserted against. Net effect ≈ Record<string, unknown>, plus a drift liability: change DomainSecurityGroup and this copy silently rots (the same flaw flagged on GuidedSetupItem in #96520).

Suggest: type boundaryEntries: Record<string, unknown> and delete both types. Where a named loose shape genuinely helps, use Partial<DomainSecurityGroup> — production itself already does this at Domain.ts:131.

– written by Claude on Ben's behalf

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Ben here, claude commented but just adding my actual voice here. I think that creating a new type here is a code smell.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 71fa790.

I removed DomainBoundarySecurityGroup and DomainBoundaryValue, and changed boundaryEntries to Record<string, unknown>. This keeps malformed boundary inputs explicit at the Reflect.set boundary without maintaining test-local copies of production models.

Comment thread tests/unit/DomainSelectorsTest.ts Outdated

type DomainBoundaryValue = BaseVacationDelegate | DomainBoundarySecurityGroup | boolean | number | string | null | undefined;

type DomainSecurityGroupPendingActionsBoundary = {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This type invents a top-level pendingAction field on a security-group pending-action entry — and I traced it end to end: no code path, client or server, ever produces that shape. The production type DomainSecurityGroupPendingActions correctly has no such field, and it should stay that way.

Evidence:

  • The App is the only writer of the DOMAIN_PENDING_ACTIONS store. The backend never writes it (COLLECTION_DOMAIN_PENDING_ACTIONS has zero hits in Web-Expensify lib; on failure it writes only createGroupErrors/deleteGroupErrors to DOMAIN_ERRORS, Auth.php:8337,8359). pendingAction is a client-side offline marker.
  • Every App write for a security group uses a named field, never a top-level pendingAction: update → {[settingsName]: UPDATE} (src/libs/actions/Domain.ts:1932), delete → {deleteGroup: DELETE} (:2027), create → {createGroup: ADD} (:2256).

So this boundary type exists only to construct a shape production correctly rejects. (Likely origin: the member pending-action variant does have a top-level pendingAction via GeneralDomainMemberPendingActionDomain.ts:1078 — and got copied onto the security-group case.)

The fix is in the test, not the type — see the comment on the pendingAction: DELETE line below.

– written by Claude on Ben's behalf

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 71fa790.

I removed DomainSecurityGroupPendingActionsBoundary entirely. The security-group pending-action fixtures now use the production-supported named fields instead of inventing a top-level pendingAction.

Comment thread tests/unit/DomainSelectorsTest.ts Outdated
} as unknown as OnyxEntry<DomainPendingActions>;
const domainPendingActions = createFixture(domainPendingActionsFixture);
const groupPendingActions: DomainSecurityGroupPendingActionsBoundary = {
pendingAction: CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

{pendingAction: DELETE} on a security-group entry is a shape that never ships. The real "group is being deleted" shape the App writes is {deleteGroup: DELETE} (src/libs/actions/Domain.ts:2027). Every delete-related case in this block uses the fictional pendingAction form, so the suite never exercises the shape that actually occurs — and isSecurityGroupPendingDeleteSelector only returns true here by accident, because Object.values(group).some(a => a === DELETE) happens to catch any DELETE-valued field.

Replace these inputs with the real fields ({deleteGroup: DELETE}, {createGroup: ADD}, {[settingName]: UPDATE}). They type-check against production with no boundary type at all, which deletes DomainSecurityGroupPendingActionsBoundary and makes the suite finally cover the real data.

This fiction predates the PR (the old code used {pendingAction: DELETE} as unknown as ...), so this is arguably beyond a mechanical assertion-cleanup — fine to fix here or in a fast follow-up, but the boundary type is the smoking gun that surfaced a real coverage gap.

– written by Claude on Ben's behalf

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 71fa790.

I replaced the fictional top-level pendingAction inputs with production-conforming shapes: deleteGroup: DELETE, createGroup: ADD, and named setting fields for update/delete actions. The tests now exercise the shapes written by the App while preserving the existing test-case identities.

Comment thread tests/unit/DomainSelectorsTest.ts Outdated
shared: {},
};

type DomainBoundarySecurityGroup = {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Ben here, claude commented but just adding my actual voice here. I think that creating a new type here is a code smell.

@blimpich
blimpich requested review from blimpich and ikevin127 and removed request for blimpich July 22, 2026 22:39
@ikevin127

ikevin127 commented Jul 22, 2026

Copy link
Copy Markdown
Contributor

Reviewer Checklist

  • I have verified the author checklist is complete (all boxes are checked off).
  • I verified the correct issue is linked in the ### Fixed Issues section above
  • I verified testing steps are clear and they cover the changes made in this PR
    • I verified the steps for local testing are in the Tests section
    • I verified the steps for Staging and/or Production testing are in the QA steps section
    • I verified the steps cover any possible failure scenarios (i.e. verify an input displays the correct error message if the entered data is not correct)
    • I turned off my network connection and tested it while offline to ensure it matches the expected behavior (i.e. verify the default avatar icon is displayed if app is offline)
  • I checked that screenshots or videos are included for tests on all platforms
  • I included screenshots or videos for tests on all platforms
  • I verified that the composer does not automatically focus or open the keyboard on mobile unless explicitly intended. This includes checking that returning the app from the background does not unexpectedly open the keyboard.
  • I verified tests pass on all platforms & I tested again on:
    • Android: HybridApp
    • Android: mWeb Chrome
    • iOS: HybridApp
    • iOS: mWeb Safari
    • MacOS: Chrome / Safari
  • If there are any errors in the console that are unrelated to this PR, I either fixed them (preferred) or linked to where I reported them in Slack
  • I verified proper code patterns were followed (see Reviewing the code)
    • I verified that any callback methods that were added or modified are named for what the method does and never what callback they handle (i.e. toggleReport and not onIconClick).
    • I verified that comments were added to code that is not self explanatory
    • I verified that any new or modified comments were clear, correct English, and explained "why" the code was doing something instead of only explaining "what" the code was doing.
    • I verified any copy / text that was added to the app is grammatically correct in English. It adheres to proper capitalization guidelines (note: only the first word of header/labels should be capitalized), and is either coming verbatim from figma or has been approved by marketing (in order to get marketing approval, ask the Bug Zero team member to add the Waiting for copy label to the issue)
  • If a new code pattern is added I verified it was agreed to be used by multiple Expensify engineers
  • I verified that this PR follows the guidelines as stated in the Review Guidelines
  • I verified other components that can be impacted by these changes have been tested, and I retested again (i.e. if the PR modifies a shared library or component like Avatar, I verified the components using Avatar have been tested & I retested again)
  • If a new component is created I verified that:
    • A similar component doesn't exist in the codebase
    • All props are defined accurately and each prop has a /** comment above it */
    • The file is named correctly
    • The component has a clear name that is non-ambiguous and the purpose of the component can be inferred from the name alone
    • The only data being stored in the state is data necessary for rendering and nothing else
    • For Class Components, any internal methods passed to components event handlers are bound to this properly so there are no scoping issues (i.e. for onClick={this.submit} the method this.submit should be bound to this in the constructor)
    • Any internal methods bound to this are necessary to be bound (i.e. avoid this.submit = this.submit.bind(this); if this.submit is never passed to a component event handler like onClick)
    • All JSX used for rendering exists in the render method
    • The component has the minimum amount of code necessary for its purpose, and it is broken down into smaller components in order to separate concerns and functions
  • If any new file was added I verified that:
    • The file has a description of what it does and/or why is needed at the top of the file if the code is not self explanatory
  • If a new CSS style is added I verified that:
    • A similar style doesn't already exist
    • The style can't be created with an existing StyleUtils function (i.e. StyleUtils.getBackgroundAndBorderStyle(theme.componentBG)
  • If the PR modifies code that runs when editing or sending messages, I tested and verified there is no unexpected behavior for all supported markdown - URLs, single line code, code blocks, quotes, headings, bold, strikethrough, and italic.
  • If the PR modifies a generic component, I tested and verified that those changes do not break usages of that component in the rest of the App (i.e. if a shared library or component like Avatar is modified, I verified that Avatar is working as expected in all cases)
  • If the PR modifies a component related to any of the existing Storybook stories, I tested and verified all stories for that component are still working as expected.
  • If the PR modifies a component or page that can be accessed by a direct deeplink, I verified that the code functions as expected when the deeplink is used - from a logged in and logged out account.
  • If the PR modifies the UI (e.g. new buttons, new UI components, changing the padding/spacing/sizing, moving components, etc) or modifies the form input styles:
    • I verified that all the inputs inside a form are aligned with each other.
    • I added Design label and/or tagged @Expensify/design so the design team can review the changes.
  • For any bug fix or new feature in this PR, I verified that sufficient unit tests are included to prevent regressions in this flow.
  • If the main branch was merged into this PR after a review, I tested again and verified the outcome was still expected according to the Test steps.
  • I have checked off every checkbox in the PR reviewer checklist, including those that don't apply to this PR.

@ikevin127 ikevin127 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Type-safety audit (the part that matters for this issue)

I checked every way an implementer could make the number drop without actually improving safety. All clear:

Check Result
eslint-disable @typescript-eslint/no-unsafe-type-assertion added anywhere None
New as X / as unknown as X double-casts introduced None (only 'domain_defaultSecurityGroupID' as const, a const assertion the rule does not flag)
Seatbelt baseline for this file Confirmed 56 in config/eslint/eslint.seatbelt.tsv:1981, so 56 -> 0 is credible
88 test scenarios preserved Ran npx jest tests/unit/DomainSelectorsTest.ts -> 88 passed

Two things worth calling out as actual improvements, not just relocations of unsafety:

  1. The well-formed entry options in DomainFixtureOptions are properly typed: admins?: Array<[string, number]>, securityGroups?: Array<[string, DomainSecurityGroup]>, vacationDelegates?: Record<number, BaseVacationDelegate>, lockedAccounts?: Record<number, boolean>. The old ... as unknown as OnyxEntry<Domain> threw away all value checking; the new builder enforces the value types. Net safety went up, not sideways.
  2. createFixture(fixture, overrides) uses Partial<T>, so the pending-action / errors overrides are type-checked against the real model now.

The one spot that could have hidden a cheat — the renamed keys — is legitimate. In isSecurityGroupPendingDeleteSelector tests the implementer changed pendingAction: ... to createGroup / deleteGroup / enableStrictPolicyRules. I confirmed against both the selector and the type:

  • src/selectors/Domain.ts:234 checks Object.values(groupPendingActions ?? {}).some((action) => action === DELETE) — it inspects values, not keys, so the key name is irrelevant to the result.
  • deleteGroup, createGroup, name, enableStrictPolicyRules are all real fields of DomainSecurityGroupPendingActions (src/types/onyx/DomainPendingActions.ts). The old pendingAction key was not a valid field on that type, which is exactly why the as unknown as was needed. Swapping to real fields is the correct fix, and behavior is preserved because the selector is value-based.

The boundaryEntries: Record<string, unknown> + Reflect.set escape hatch is reserved only for deliberately malformed / foreign-prefix keys (the "ignore keys that don't match the prefix", null/undefined, someOtherKey cases). That is unavoidable — those tests exist to prove the selector ignores garbage — and scoping the untyped injection to just those entries while keeping the base fixture typed is the honest way to do it.

Non-blocking findings

🟠 Seatbelt TSV is intentionally not committed — confirm the count actually locks in. The baseline row still reads 56, and the whole payout is measured by that count. Confirm the repo's post-merge automation actually tightens 56 -> 0 on main (the author's stated assumption). If it does not, the baseline stays loose (allows up to 56 again) and the reduction is not locked in even though the file is clean. This is a process risk, not a code issue, but it is the one item most worth confirming for this payout structure.

🟡 Base-fixture pollution changes what the fixtures represent. createDomainFixture() seeds every non-empty domain with {validated: true, accountID: 1, email: 'test@example.com', domain_defaultSecurityGroupID: ''}. Tests like the admin / member / vacation-delegate ones previously used bare objects with only the prefixed keys under test. It is harmless today because every selector filters by key prefix, so the four base props are always ignored, and all 88 tests pass. But it weakens the 1:1 correspondence between the fixture and the scenario, and it is a latent trap: the moment a selector reads validated or accountID, a test that meant "bare domain" would silently carry values. Preferred fix: have the builder start from {} and add base identity fields only when a test opts in (the selectSecurityGroupForAccount cases that need validated/accountID/email).

🟢 Readability trade-off. The createDomainFixture builder (9 options, Reflect.set / Reflect.deleteProperty loops) is heavier than the inline literals it replaces. For test data, inline literals are often easier to review because you see the exact shape. This is the cost the issue mandates, so acceptable, but the file did get harder to skim.

🟢 createFixture returns T after deleting a required prop. e.g.

const domainMemberSharedNVP = createFixture(cardFeedsFixture);
Reflect.deleteProperty(domainMemberSharedNVP, 'settings');

The variable is still statically typed CardFeeds (with settings) while the runtime object has no settings. It works because the selector optional-chains, but the static type now lies. The safety here is runtime-honest, not type-honest. Minor, tolerable in a test.

cc @KJ21-ENG

Net: Clean, honest work that removes 56 assertions the right way. The 🟡 / 🟢 items are polish, and the 🟠 is a process confirmation rather than a code defect, no merge-blockers.

@melvin-bot
melvin-bot Bot requested a review from blimpich July 23, 2026 00:36
@blimpich
blimpich merged commit c36264b into Expensify:main Jul 23, 2026
31 checks passed
@OSBotify

Copy link
Copy Markdown
Contributor

🚀 Deployed to staging by https://github.com/blimpich in version: 9.4.44-0 🚀

platform result
🕸 web 🕸 success ✅
🤖 android 🤖 success ✅
🍎 iOS 🍎 success ✅

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