Skip to content

Commit

Permalink
Set up Cypress and configure local test environment (#829)
Browse files Browse the repository at this point in the history
* Testing : Intial cypress setup

* Added test for card component

* Added dummy e2e tests

* setup cypress code coverage

* Improved code coverage for card component to 100%

* updated eslint & fixes error after merge conflict

* cleanup(ci.yml): removed build job from ci.yml

* Add test and coverage job
  • Loading branch information
aialok authored Jul 31, 2024
1 parent e4305fe commit f6dff53
Show file tree
Hide file tree
Showing 15 changed files with 2,204 additions and 108 deletions.
4 changes: 3 additions & 1 deletion .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ module.exports = {
es2021: true,
node: true,
browser: true,
"cypress/globals": true
},
settings: {
react: {
Expand All @@ -16,6 +17,7 @@ module.exports = {
'plugin:react-hooks/recommended',
'plugin:@next/next/recommended',
'plugin:prettier/recommended',
'plugin:cypress/recommended',
],
parser: '@typescript-eslint/parser',
parserOptions: {
Expand All @@ -25,7 +27,7 @@ module.exports = {
ecmaVersion: 12,
sourceType: 'module',
},
plugins: ['react', '@typescript-eslint', 'prettier'],
plugins: ['react', '@typescript-eslint', 'prettier', 'cypress'],
rules: {
'array-bracket-spacing': ['error', 'never'],
'object-curly-spacing': ['error', 'always'],
Expand Down
53 changes: 20 additions & 33 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@ on:
pull_request:
types: [opened, reopened, synchronize]

env:
CODECOV_UNIQUE_NAME: CODECOV_UNIQUE_NAME-${{ github.run_id }}-${{ github.run_number }}

jobs:
code-quality-checks:
name: Code Quality Checks
Expand Down Expand Up @@ -92,51 +95,35 @@ jobs:
done
exit 1
build:
name: Build check
needs: code-quality-checks
testing-and-coverage:
name: Testing and Coverage
needs: [code-quality-checks]
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
submodules: recursive

- name: Get yarn cache directory path
id: yarn-cache-dir-path
run: echo "dir=$(yarn cache dir)" >> $GITHUB_OUTPUT

- name: Cache Node dependencies
uses: actions/cache@v4
id: yarn-cache
with:
path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
restore-keys: |
${{ runner.os }}-yarn-
- if: ${{ steps.yarn-cache.outputs.cache-hit != 'true' }}
name: List the state of node modules
continue-on-error: true
run: yarn list

- name: Cache Next Build
uses: actions/cache@v4
with:
path: |
${{ steps.yarn-cache-dir-path.outputs.dir }}
${{ github.workspace }}/.next/cache
key: ${{ runner.os }}-nextjs-${{ hashFiles('**/yarn.lock') }}-${{ hashFiles('**/*.js', '**/*.jsx', '**/*.ts', '**/*.tsx') }}
restore-keys: |
${{ runner.os }}-nextjs-${{ hashFiles('**/yarn.lock') }}-
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: 20
cache: 'yarn'

- name: Install dependencies
run: yarn install --frozen-lockfile

- name: Build
run: yarn run build
- name: Run development server
run: yarn run dev &

- name: Run tests and generate coverage report
run: yarn run test:coverage:all

- name: Upload coverage report to Codecov
uses: codecov/codecov-action@v2
with:
token: ${{ secrets.CODECOV_TOKEN }}
name: ${{ env.CODECOV_UNIQUE_NAME }}
verbose: true
fail_ci_if_error: true
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@

# testing
/coverage
/.nyc_output
coverage.json

# next.js
/.next/
Expand Down
22 changes: 17 additions & 5 deletions components/Card.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import React from 'react';
import Link from 'next/link';
import TextTruncate from 'react-text-truncate';
interface CardProps {
export interface CardProps {
title: string;
body: string;
icon?: string;
Expand Down Expand Up @@ -35,29 +35,41 @@ const CardBody = ({
return (
<div className='group relative h-full w-full rounded-lg border border-gray-200 bg-white p-6 px-12 shadow-3xl dark:shadow-2xl dark:shadow-slate-900 transition-colors ease-in-out hover:bg-slate-100 dark:bg-slate-800 hover:dark:bg-slate-900/30'>
<div className='flex justify-center '>
{image && <img src={image} className='h-32 p-2' />}
{image && (
<img src={image} className='h-32 p-2' data-test='card-image' />
)}
</div>
<div className='flex flex-row items-start mb-6'>
{icon && (
<span className='mr-6 flex h-14 w-14 flex-shrink-0 items-center justify-center rounded-lg border bg-blue-200 px-3 text-gray-900 dark:text-white'>
<img src={icon} alt={title} className='h-full w-full' />
<img
src={icon}
alt={title}
className='h-full w-full'
data-test='card-icon'
/>
</span>
)}
<p
className={`mb-1 mt-1 items-center font-bold text-gray-900 dark:text-white ${headerSizeClasses[headerSize || 'medium']}`}
data-test='card-title'
>
{title}
</p>
</div>
<hr className='mb-4 mt-3.5 h-px border-0 bg-gray-400' />
<p
className={`mb-8 text-black mt-5 dark:text-white ${bodyTextSizeClasses[bodyTextSize || 'medium']} `}
data-test='card-body'
>
{extended && <span dangerouslySetInnerHTML={{ __html: body }} />}
{!extended && <TextTruncate element='span' line={3} text={body} />}
</p>
{link && (
<p className='absolute bottom-3 right-5 font-medium opacity-0 transition-opacity delay-150 ease-in-out group-hover:opacity-100 text-black dark:text-white '>
<p
className='absolute bottom-3 right-5 font-medium opacity-0 transition-opacity delay-150 ease-in-out group-hover:opacity-100 text-black dark:text-white'
data-test='card-read-more'
>
Read More
</p>
)}
Expand All @@ -78,7 +90,7 @@ const Card: React.FC<CardProps> = ({
return (
<>
{link ? (
<Link href={link}>
<Link href={link} data-test='card-link'>
<CardBody
{...{
title,
Expand Down
23 changes: 23 additions & 0 deletions cypress.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { defineConfig } from 'cypress';

export default defineConfig({
component: {
devServer: {
framework: 'next',
bundler: 'webpack',
},
specPattern: 'cypress/components/**/*.cy.{js,jsx,ts,tsx}',
setupNodeEvents(on, config) {
// eslint-disable-next-line @typescript-eslint/no-var-requires
require('@cypress/code-coverage/task')(on, config);
return config;
},
},
e2e: {
setupNodeEvents(on, config) {
// eslint-disable-next-line @typescript-eslint/no-var-requires
require('@cypress/code-coverage/task')(on, config);
return config;
},
},
});
73 changes: 73 additions & 0 deletions cypress/components/Card.cy.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import React from 'react';
import Card from '../../components/Card';
import { CardProps } from '../../components/Card';

const RoadmapProps: CardProps = {
icon: '/icons/roadmap.svg',
title: 'Roadmap',
body: 'Explore our exciting plans and upcoming milestones. 🚀',
headerSize: 'large',
bodyTextSize: 'medium',
link: 'https://github.com/orgs/json-schema-org/discussions/427',
};

describe('Card Component', () => {
// Render the Roadmap Card with default RoadmapProps
it('should render Roadmap Card correctly', () => {
cy.mount(<Card {...RoadmapProps} />);
cy.get('[data-test="card-image"]').should('not.exist');
cy.get('[data-test="card-icon"]').should(
'have.attr',
'src',
RoadmapProps.icon,
);
cy.get('[data-test="card-title"]').should('have.text', RoadmapProps.title);
cy.get('[data-test="card-body"]').should('have.text', RoadmapProps.body);
cy.get('[data-test="card-read-more"]').should('have.text', 'Read More');
cy.get('[data-test="card-link"]').should(
'have.attr',
'href',
RoadmapProps.link,
);
cy.get('[data-test="card-title"]').should('have.class', 'text-[2rem]');
cy.get('[data-test="card-body"]').should('have.class', 'text-[1rem]');
});

// Render the Roadmap card with default header and body sizes
it('should render Roadmap card with default header and body sizes', () => {
const missingSizes = {
...RoadmapProps,
headerSize: undefined,
bodyTextSize: undefined,
};
cy.mount(<Card {...missingSizes} />);
cy.get('[data-test="card-title"]').should('have.class', 'text-[1.3rem]');
cy.get('[data-test="card-body"]').should('have.class', 'text-[1rem]');
});

// Render the Roadmap card with extended body text
it('should render Roadmap card with extended body text', () => {
const extendedBody = { ...RoadmapProps, extended: true };
cy.mount(<Card {...extendedBody} />);
cy.get('[data-test="card-body"]').find('span').should('exist');
});

// Render the Roadmap card with image
it('should render Roadmap card with image', () => {
const imageProps = { ...RoadmapProps, image: '/icons/roadmap.svg' };
cy.mount(<Card {...imageProps} />);
cy.get('[data-test="card-image"]').should(
'have.attr',
'src',
imageProps.image,
);
});

// Render the Roadmap Card with some missing props
it('should render Roadmap card with some missing props correctly', () => {
const missingProps = { ...RoadmapProps, icon: undefined, link: undefined };
cy.mount(<Card {...missingProps} />);
cy.get('[data-test="card-icon"]').should('not.exist');
cy.get('[data-test="card-link"]').should('not.exist');
});
});
7 changes: 7 additions & 0 deletions cypress/e2e/homepage.cy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
// describe('Homepage', () => {
// it('should contains - Build more. Break less. Empower others.', () => {
// cy.viewport(1280, 720);
// cy.visit('http://localhost:3000');
// cy.contains(/Build more. Break less. Empower others./i);
// });
// });
37 changes: 37 additions & 0 deletions cypress/support/commands.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
/// <reference types="cypress" />
// ***********************************************
// This example commands.ts shows you how to
// create various custom commands and overwrite
// existing commands.
//
// For more comprehensive examples of custom
// commands please read more here:
// https://on.cypress.io/custom-commands
// ***********************************************
//
//
// -- This is a parent command --
// Cypress.Commands.add('login', (email, password) => { ... })
//
//
// -- This is a child command --
// Cypress.Commands.add('drag', { prevSubject: 'element'}, (subject, options) => { ... })
//
//
// -- This is a dual command --
// Cypress.Commands.add('dismiss', { prevSubject: 'optional'}, (subject, options) => { ... })
//
//
// -- This will overwrite an existing command --
// Cypress.Commands.overwrite('visit', (originalFn, url, options) => { ... })
//
// declare global {
// namespace Cypress {
// interface Chainable {
// login(email: string, password: string): Chainable<void>
// drag(subject: string, options?: Partial<TypeOptions>): Chainable<Element>
// dismiss(subject: string, options?: Partial<TypeOptions>): Chainable<Element>
// visit(originalFn: CommandOriginalFn, url: string, options: Partial<VisitOptions>): Chainable<Element>
// }
// }
// }
14 changes: 14 additions & 0 deletions cypress/support/component-index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>Components App</title>
<!-- Used by Next.js to inject CSS. -->
<div id="__next_css__DO_NOT_USE__"></div>
</head>
<body>
<div data-cy-root></div>
</body>
</html>
39 changes: 39 additions & 0 deletions cypress/support/component.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
// ***********************************************************
// This example support/component.ts is processed and
// loaded automatically before your test files.
//
// This is a great place to put global configuration and
// behavior that modifies Cypress.
//
// You can change the location of this file or turn off
// automatically serving support files with the
// 'supportFile' configuration option.
//
// You can read more here:
// https://on.cypress.io/configuration
// ***********************************************************

// Import commands.js using ES2015 syntax:
import './commands';
import '@cypress/code-coverage/support';
import { mount } from 'cypress/react18';
import '../../styles/globals.css';

// Augment the Cypress namespace to include type definitions for
// your custom command.
// Alternatively, can be defined in cypress/support/component.d.ts
// with a <reference path="./component" /> at the top of your spec.

declare global {
// eslint-disable-next-line @typescript-eslint/no-namespace
namespace Cypress {
interface Chainable {
mount: typeof mount;
}
}
}

Cypress.Commands.add('mount', mount);

// Example use:
// cy.mount(<MyComponent />)
18 changes: 18 additions & 0 deletions cypress/support/e2e.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
// ***********************************************************
// This example support/e2e.ts is processed and
// loaded automatically before your test files.
//
// This is a great place to put global configuration and
// behavior that modifies Cypress.
//
// You can change the location of this file or turn off
// automatically serving support files with the
// 'supportFile' configuration option.
//
// You can read more here:
// https://on.cypress.io/configuration
// ***********************************************************

// Import commands.js using ES2015 syntax:
import './commands';
import '@cypress/code-coverage/support';
Loading

0 comments on commit f6dff53

Please sign in to comment.