cypress-bootstrap
Version:
Cypress Bootstrap is a project scaffolding tool that sets up a Cypress automation framework with a standardized folder structure and Page Object Model (POM) design. It helps teams quickly start testing with built-in best practices and sample specs.
338 lines (241 loc) • 12.3 kB
Markdown
# Cypress Bootstrap
A comprehensive test automation framework built with Cypress and TypeScript, following the Page Object Model (POM) design pattern. This framework is designed to be used as an npm package that can be installed in any project. It includes sample tests for the [Sauce Demo](https://www.saucedemo.com/) website that you can use as a reference. The intention is to enforce the best practices of test automation and to provide a solid foundation for building scalable and maintainable test frameworks and test suites.
This framework consist of sample tests for the Sauce Demo website and API tests for the `subscription` API project included in the project.
You can use these tests as a reference for your own learning. Then you can simply delete the same tests and start from scratch for your project.
## Features
- **Page Object Model**: Well-structured page objects for better maintainability and reusability
- **TypeScript Support**: Strong typing for better code quality and developer experience
- **Test Data Management**: External JSON files for test data
- **Reporting**: Integrated with Mochawesome for detailed HTML reports
- **CI/CD Integration**: Ready for continuous integration with parallel test execution
- **Custom Commands**: Extended Cypress commands for common operations
- **Test Filtering**: Using tags to run specific test suites
- **API Testing**: Support for API testing with schema validation
- **Session Management**: Efficient handling of authentication and sessions
- **Accessibility Testing**: Support for accessibility testing with `wick-a11y` plugin using `axe-core` library
## Prerequisites
- Node.js (v14 or higher)
- npm (v6 or higher)
## Installation
Initiate a new Node.js project:
```bash
npm init -y
```
Then, install the package in your project:
```bash
npm install cypress-bootstrap
```
Then run the below command to setup the framework:
```bash
# Option 1: Run the setup script directly
npx cypress-bootstrap-setup
# Option 2: Use the npm script
npm run setup
```
After installation, the package will automatically:
1. Set up the required directory structure
2. Copy the necessary configuration files to your project (including Prettier and Husky configurations)
3. Install all required dependencies (including Prettier, Husky, and lint-staged)
4. Configure the pre-commit hook for automatic code formatting
This process ensures that your project is ready to use with all the necessary dependencies installed and code formatting tools configured. You can then customize the files to suit your needs.
## Configuration
The framework can be configured using the following files:
- `cypress.config.ts`: Main Cypress configuration
- `cypress.env.json`: Environment-specific variables (not committed to version control)
- `reporter-config.ts`: Reporting configuration
## Project Structure
After installation, the following directory structure will be created in your project:
```
├── cypress/
│ ├── downloads/ # Downloaded files during test execution
│ ├── pages/ # Page Object Model classes
│ ├── reports/ # Test execution reports generated by Mochawesome
│ ├── screenshots/ # Screenshots taken during test failures
│ ├── support/ # Support files (commands, e2e.ts, plugins)
│ ├── testbase/ # Base classes and test setup
│ ├── testdata/ # Test data files
│ ├── tests/ # Test files
│ │ ├── ui/ # UI tests
│ │ └── api/ # API tests
│ └── videos/ # Videos recorded during test execution
├── .husky/ # Husky Git hooks configuration
│ └── pre-commit # Pre-commit hook for automatic formatting
├── node_modules/
├── .gitignore
├── .prettierrc # Prettier configuration file
├── .prettierignore # Files to be excluded from Prettier formatting
├── cypress.config.ts
├── cypress.env.json
├── package.json
├── package-lock.json
├── reporter-config.ts
└── tsconfig.json
```
## Customization
The following files and directories can be modified to suit your needs:
- `cypress.config.ts`: Customize Cypress configuration
- `cypress/testbase/`: Modify base classes and test setup
- `cypress/testdata/`: Add or modify test data
- `cypress/tests/`: Add or modify test files
- `cypress/pages/`: Add or modify Page Object Model classes
- `cypress/support/`: Modify support files and custom commands
- `tsconfig.json`: Customize TypeScript configuration
- `reporter-config.ts`: Customize reporting configuration
These files are copied to your project during installation and can be modified without affecting the original package. And future updates to the package will not overwrite your customizations.
## Support Files
The framework includes essential support files in the `cypress/support` directory:
- `e2e.ts`: The default support file required by Cypress for e2e testing
- `commands.ts`: Custom Cypress commands that extend the default functionality
- `Enums.ts`: Enumeration types used throughout the framework
- `index.d.ts`: TypeScript type definitions for the framework
- `types/`: Additional TypeScript type definitions
These files are automatically copied to your project during installation. The `e2e.ts` file is particularly important as Cypress expects this file to exist by default. If this file is missing, Cypress will display an error message when you try to run tests.
## Code Formatting
The framework uses Prettier for consistent code formatting. The configuration is defined in the `.prettierrc` file, and certain files/directories are excluded from formatting in the `.prettierignore` file. These configuration files are automatically included when you install the package and copied to your project during setup.
### Automatic Formatting with Husky
The framework includes Husky and lint-staged to automatically format your code when you commit changes. This ensures that all committed code follows the project's formatting standards. The Husky configuration (`.husky` directory) is included in the package and set up automatically in your project.
When you make a commit, the pre-commit hook will:
1. Check which files are staged for commit
2. Run Prettier on those files
3. Stage the formatted files
This happens automatically and requires no manual intervention.
### Manual Formatting Commands
To manually format all code files in the project:
```bash
npm run format
```
To check if all files are properly formatted without making changes:
```bash
npm run format:check
```
## Setting up to Run Tests
## Setup Scripts
After installing the package, you'll need to add the following scripts to your project's package.json file:
```json
{
"scripts": {
"cypress:run": "cypress run",
"cypress:cloud:run": "cypress run --record --parallel",
"cypress:open": "cypress open",
"format": "prettier --write \"**/*.{js,ts,tsx,json,md}\"",
"format:check": "prettier --check \"**/*.{js,ts,tsx,json,md}\"",
"prepare": "husky"
},
"lint-staged": {
"**/*.{js,ts,tsx,json,md}": ["prettier --write"]
}
}
```
### Start the Subscription API Server
Then if you want to try out the API tests, you need to navigate to the `subscription` project and run the following command:
```bash
cd subscription-api
npm install
npm start
```
This will start the `subsription` API server on port `3000`.
## Running Tests
Then you can run tests using the following commands:
### Open Cypress Test Runner
```bash
npm run cypress:open
```
### Run All Tests Headlessly
```bash
npm run cypress:run
```
### Run Tests in Cypress Cloud with Parallelization
```bash
npm run cypress:cloud:run
```
### Run Tests with Tags
```bash
npx cypress run --env grepTags=@smoke
```
### Creating Your First Test
1. Create a new test file in the `cypress/tests/ui` directory:
```typescript
// cypress/tests/ui/example_test.spec.ts
import LoginPage from '../../pages/LoginPage';
import InventoryPage from '../../pages/InventoryPage';
import TestData from '../../testdata/testdata.json';
describe('Example Test', () => {
it('should demonstrate how to use the framework', () => {
// Your test code here
cy.visit('/');
// Use the Page Object Model pattern
// Use test data from the testdata directory
});
});
```
2. Run the test using one of the commands above.
## Page Object Model
The framework implements the Page Object Model pattern with:
- `BasePage.ts`: Base class with common functionality
- Page classes (e.g., `LoginPage.ts`, `InventoryPage.ts`): Specific page implementations
- Test files: Using the page objects to interact with the application
Example:
```typescript
// Test file
import LoginPage from '../../pages/LoginPage';
import InventoryPage from '../../pages/InventoryPage';
import TestData from '../../testdata/testData.json';
describe('Login Test', () => {
it('should login successfully', () => {
LoginPage.visit('/');
LoginPage.login(TestData.user_credentials.valid_username, TestData.user_credentials.password);
InventoryPage.checkPageURL('/inventory.html');
});
});
```
## Test Data Management
Test data is stored in JSON files in the `cypress/testdata` directory:
```json
{
"user_credentials": {
"valid_username": "standard_user",
"locked_out_user": "locked_out_user",
"password": "secret_sauce"
}
}
```
## Reporting
The framework uses Mochawesome for HTML reports and supports JUnit XML reports for CI/CD integration. When you run the tests in headless mode, the reports will be generated in the `cypress/reports` directory.
## Utility Functions
The framework includes a Utils class that provides several utility functions you can use in your tests:
```typescript
import Utils from '../../testbase/Utils';
// Generate a random ID number
const randomId = Utils.generateRandomIdNumber();
// Generate a random string
const randomString = Utils.generateRandomString(10); // Length parameter is required
// Generate a random GUID
const guid = Utils.generateGuid();
```
These utility functions can be used in your test files to generate random data for testing purposes.
## Accessibility Testing
The framework includes support for accessibility testing using the `wick-a11y` plugin which uses the `axe-core` library. You can run accessibility tests in your test files as follows:
Define the accessibility standards you want to check against in the test file. Then inject and check for accessibility violations:
```typescript
const a11yOptions = { runOnly: ['wcag2a', 'wcag2aa'] };
describe('Accessibility Test', () => {
before(() => {
cy.visit('/');
cy.injectAxe();
});
it('should have no accessibility violations', () => {
cy.checkAccessibility(undefined, a11yOptions);
});
});
```
## Documentation
Comprehensive documentation for this framework is available in the `docs` directory:
- [Documentation Index](https://github.com/s-chathuranga-j/cypress-advanced-framework/blob/c98ed9d48e0524563ee5dad1d6961be55bfc5645/docs/overview.md): Table of contents and overview
- [Project Overview](https://github.com/s-chathuranga-j/cypress-advanced-framework/blob/c98ed9d48e0524563ee5dad1d6961be55bfc5645/docs/project-overview.md): Architecture and key features
- [Page Object Model Implementation](https://github.com/s-chathuranga-j/cypress-advanced-framework/blob/c98ed9d48e0524563ee5dad1d6961be55bfc5645/docs/page-object-model.md): Details on the POM pattern
- [Test Organization](https://github.com/s-chathuranga-j/cypress-advanced-framework/blob/c98ed9d48e0524563ee5dad1d6961be55bfc5645/docs/test-organization.md): Guidelines for organizing tests
- [API Testing Approach](https://github.com/s-chathuranga-j/cypress-advanced-framework/blob/c98ed9d48e0524563ee5dad1d6961be55bfc5645/docs/api-testing.md): Information on API testing
- [Configuration and Setup](https://github.com/s-chathuranga-j/cypress-advanced-framework/blob/c98ed9d48e0524563ee5dad1d6961be55bfc5645/docs/configuration.md): Setup and configuration details
These documents provide detailed instructions on how to follow the patterns and best practices implemented in this framework.
## License
MIT