Cypress Testing

Learn ways to use Cypress with Knapsack.
View as Markdown

Overview

Knapsack easily integrates with Cypress, providing a powerful testing framework for your design system components. In this documentation, we illustrate how you can leverage the pattern manifest alongside a custom utility function to streamline your testing process. These examples demonstrate effective strategies for dynamically accessing and validating your component variations within Cypress.

Example Utility Function: ksDemo()

This example ksDemo() function is a helper that parses the Knapsack pattern manifest and retrieves the URL for a specific variation based on the provided identifiers. It assumes the cypress directory is in the root alongside the Knapsack dist directory (where the manifest resides).

1// Import all Knapsack demo variations
2import variations from '../../dist/meta/ks-meta.json'
3
4// Define the ksDemo function to filter and return the specific variation URL
5export const ksDemo = (
6 patternId,
7 templateId,
8 demoId,
9 assetSetId = 'default'
10) => {
11 const specificVariation = variations.demoUrls.filter((item) => {
12 return (
13 item.templateId === templateId &&
14 item.demoId === demoId &&
15 item.assetSetId === assetSetId &&
16 item.patternId === patternId
17 )
18 })
19 return specificVariation[0].url
20}

Implementation in Cypress:

1/// <reference types="cypress" />
2
3import { ksDemo } from '../../support/knapsack'
4
5describe('Button component (React > Main)', () => {
6 beforeEach(() => {
7 cy.visit(ksDemo('button', 'react', 'YsCbuprpiV'))
8 })
9
10 it('contains text (is not empty)', () => {
11 cy.get('.MuiButtonBase').should('not.be.empty')
12 })
13})

Finding the Pattern ID

To determine the pattern ID necessary for testing, you can extract it from the URL query string parameters.

For example, given the following URL:

https://app.knapsack.cloud/site/acme-design-system/latest/pattern/button?templateId=react&demoId=YsCbuprpiV

The pattern ID for the React Button component’s main demo is YsCbuprpiV:

1ksDemo('button', 'react', 'YsCbuprpiV');