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).

// Import all Knapsack demo variations
import variations from '../../dist/meta/ks-meta.json'
// Define the ksDemo function to filter and return the specific variation URL
export const ksDemo = (
patternId,
templateId,
demoId,
assetSetId = 'default'
) => {
const specificVariation = variations.demoUrls.filter((item) => {
return (
item.templateId === templateId &&
item.demoId === demoId &&
item.assetSetId === assetSetId &&
item.patternId === patternId
)
})
return specificVariation[0].url
}

Implementation in Cypress:

/// <reference types="cypress" />
import { ksDemo } from '../../support/knapsack'
describe('Button component (React > Main)', () => {
beforeEach(() => {
cy.visit(ksDemo('button', 'react', 'YsCbuprpiV'))
})
it('contains text (is not empty)', () => {
cy.get('.MuiButtonBase').should('not.be.empty')
})
})

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:

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