Skip to content

Commit

Permalink
Added type safety to custom data-cy command
Browse files Browse the repository at this point in the history
As data-cy attributes are the preferred way to select element within Cypress, I've enhanced the custom `cy.dataCy()` command to use constants instead of a string. This ensures that custom data selectors cannot have typos or accidential changes.

To make this work, I had to consolidate cypress.d.ts and commands.ts as a d.ts file cannot import other files dynamically.
  • Loading branch information
JacobArrow committed Jan 7, 2025
1 parent 060d62d commit 4d62af4
Show file tree
Hide file tree
Showing 5 changed files with 20 additions and 10 deletions.
3 changes: 2 additions & 1 deletion components/global/header/Header.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import DarkModeToggle from "@/components/shared/darkModeToggle/DarkModeToggle"
import Icon from "@/components/shared/icon/Icon"
import SearchInput from "@/components/shared/searchInput/SearchInput"
import SmartLink from "@/components/shared/smartLink/SmartLink"
import { cyKeys } from "@/cypress/support/constants"

import ProfileButton from "./ProfileButton"

Expand All @@ -15,7 +16,7 @@ function Header() {
<p className="text-typo-caption">Biblioterernes ebøger og lydbøger</p>
</div>
<div className="content-container grid h-navigation-height grid-cols-3 items-center">
<div className="flex-0 flex items-center">
<div className="flex-0 flex items-center" data-cy={cyKeys["go-logo"]}>
<Button ariaLabel="Gå til forsiden" asChild className="inline-flex px-3">
<SmartLink href="/" className="inline-flex">
<Icon name="logo-borderless" />
Expand Down
8 changes: 0 additions & 8 deletions cypress/cypress.d.ts

This file was deleted.

1 change: 1 addition & 0 deletions cypress/e2e/frontpage.cy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,6 @@ describe("Front Page Tests", () => {

cy.get("header").should("exist")
cy.get("footer").should("exist")
cy.dataCy("go-logo").should("exist")
})
})
13 changes: 12 additions & 1 deletion cypress/support/commands.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,14 @@
Cypress.Commands.add("dataCy", (selector: string) => {
/* eslint-disable @typescript-eslint/no-namespace */
import { CyKey } from "./constants"

declare global {
namespace Cypress {
interface Chainable {
dataCy(value: CyKey): Chainable<JQuery<HTMLElement>>
}
}
}

Cypress.Commands.add("dataCy", selector => {
return cy.get(`[data-cy="${selector}"]`)
})
5 changes: 5 additions & 0 deletions cypress/support/constants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export const cyKeys = {
"go-logo": "go-logo",
} as const

export type CyKey = keyof typeof cyKeys

0 comments on commit 4d62af4

Please sign in to comment.