PR-440978: Adding Cypress Component Testing.

This commit is contained in:
Alejandro Lembke Barrientos 2023-03-03 08:27:25 -06:00
parent d76372d1e0
commit 24987d7c09
17 changed files with 2252 additions and 69 deletions

View File

@ -14,9 +14,19 @@ jobs:
registry-url: https://registry.npmjs.org/
- run: npm ci --legacy-peer-deps
- run: npm test
cypress-run:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v3
# Install NPM dependencies, cache them correctly
# and run all Cypress tests
- name: Cypress run
uses: cypress-io/github-action@v5 # use the explicit version number
with:
start: npm run cy:run
publish-npm:
needs: build
needs: [ build, cypress-run ]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3

View File

@ -20,8 +20,19 @@ jobs:
registry-url: https://registry.npmjs.org/
- run: npm ci --legacy-peer-deps
- run: npm test
cypress-run:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v3
# Install NPM dependencies, cache them correctly
# and run all Cypress tests
- name: Cypress run
uses: cypress-io/github-action@v5 # use the explicit version number
with:
start: npm run cy:run
test-build-package:
needs: test
needs: [ test, cypress-run ]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3

15
cypress.config.ts Normal file
View File

@ -0,0 +1,15 @@
import { defineConfig } from "cypress";
import webpackConfig from './webpack.cy.config';
export default defineConfig({
component: {
specPattern: 'src/**/*.cy.{js,jsx,ts,tsx}',
devServer: {
framework: "react",
bundler: "webpack",
webpackConfig: webpackConfig,
},
viewportWidth: 1280,
viewportHeight: 720,
},
});

View File

@ -0,0 +1,5 @@
{
"name": "Using fixtures to represent data",
"email": "hello@cypress.io",
"body": "Fixtures are a great way to mock data for responses to routes"
}

View File

@ -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>
// }
// }
// }

View File

@ -0,0 +1,12 @@
<!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>
</head>
<body>
<div data-cy-root></div>
</body>
</html>

View File

@ -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'
// Alternatively you can use CommonJS syntax:
// require('./commands')
import { mount } from 'cypress/react18'
// 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 {
namespace Cypress {
interface Chainable {
mount: typeof mount
}
}
}
Cypress.Commands.add('mount', mount)
// Example use:
// cy.mount(<MyComponent />)

View File

@ -1,10 +1,17 @@
const { pathsToModuleNameMapper } = require('ts-jest');
const { compilerOptions } = require('./tsconfig');
const aliases = pathsToModuleNameMapper(compilerOptions.paths, {
prefix: '<rootDir>'
});
module.exports = {
setupFilesAfterEnv: ['<rootDir>/setupTest.ts'],
"testEnvironment": "jsdom",
testPathIgnorePatterns: ['/node_modules/', '\\.cy.(js|jsx|ts|tsx)$'],
testEnvironment: 'jsdom',
moduleNameMapper: {
"\\.(jpg|ico|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/src/__mocks__/fileMock.ts",
"\\.(css|sass|scss|less)$": "identity-obj-proxy"
...aliases,
'\\.(jpg|ico|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$': '<rootDir>/src/__mocks__/fileMock.ts',
'\\.(css|sass|scss|less)$': 'identity-obj-proxy'
},
};

2007
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,6 +1,6 @@
{
"name": "@aleleba/create-react-component-library",
"version": "1.1.18",
"version": "1.2.0",
"description": "A starter kit for create a React component Library with storybook",
"bin": "./bin/cli.js",
"main": "dist/index.js",
@ -13,7 +13,9 @@
"test:watch": "jest --watch",
"storybook": "start-storybook -p 3000",
"build-storybook": "build-storybook",
"check-updates": "npx npm-check-updates -u && npm i --legacy-peer-deps"
"check-updates": "npx npm-check-updates -u && npm i --legacy-peer-deps",
"cy:open": "npx cypress open",
"cy:run": "npx cypress run --headless --component"
},
"repository": {
"type": "git",
@ -63,11 +65,13 @@
"clean-webpack-plugin": "^4.0.0",
"css-loader": "^6.7.3",
"css-minimizer-webpack-plugin": "^4.2.2",
"cypress": "^12.7.0",
"dotenv": "^16.0.3",
"eslint": "^8.35.0",
"eslint-plugin-react": "^7.32.2",
"eslint-plugin-storybook": "^0.6.11",
"eslint-webpack-plugin": "^4.0.0",
"html-webpack-plugin": "^5.5.0",
"identity-obj-proxy": "^3.0.0",
"jest": "^29.4.3",
"jest-environment-jsdom": "^29.4.3",
@ -75,11 +79,12 @@
"mini-css-extract-plugin": "^2.7.2",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"resolve-ts-aliases": "^1.0.1",
"sass": "^1.58.3",
"sass-loader": "^13.2.0",
"style-loader": "^3.3.1",
"terser-webpack-plugin": "^5.3.6",
"ts-loader": "^9.4.2",
"ts-jest": "^29.0.5",
"tsconfig-paths-webpack-plugin": "^4.0.0",
"typescript": "^4.9.5",
"url-loader": "^4.1.1",

View File

@ -1,4 +1,4 @@
declare module "*.svg" {
const content: any;
export default content;
}
}

View File

@ -0,0 +1,14 @@
import React from 'react';
import { Card } from '@components';
describe('Testing Card Component', () => {
beforeEach(() => {
cy.mount(<Card title='Test Title'><p>Test Content</p></Card>);
})
it('Show Title', () => {
cy.get('div').contains('Test Title');
})
it('Show Child Component', () => {
cy.get('p').contains('Test Content');
})
})

View File

@ -1,20 +1,24 @@
import React from 'react';
import { render } from '@testing-library/react';
import { Card } from '../Card';
import { render, screen } from '@testing-library/react';
import { Card } from '@components';
describe('<App/> Component', () => {
beforeEach(() => {
fetchMock.resetMocks();
// fetchMock.resetMocks();
render(<Card title='Test Title'><p>Test Content</p></Card>)
});
test('Should render <Card /> Component', async () => {
fetchMock.mockResponseOnce(JSON.stringify({
it('Show Title', async () => {
/* fetchMock.mockResponseOnce(JSON.stringify({
//First Data Fetch
data: 'data'
}));
render(
<Card title='Test Title'><p>Test Content</p></Card>
)
})); */
screen.getByText('Test Title')
})
})
it('Show Child Component', async () => {
/* fetchMock.mockResponseOnce(JSON.stringify({
//First Data Fetch
data: 'data'
})); */
screen.getByText('Test Content')
})
})

View File

@ -1,7 +1,6 @@
import React from 'react';
import { ComponentStory, ComponentMeta } from '@storybook/react';
import { Card } from '@components/Card';
import { Card } from '@components';
// More on default export: https://storybook.js.org/docs/react/writing-stories/introduction#default-export
export default {

View File

@ -23,16 +23,18 @@
"types": [
"react/next",
"react-dom/next",
"node"
"node",
"cypress"
],
"sourceMap": true,
"baseUrl": "src",
"baseUrl": ".",
"outDir": "dist",
"skipLibCheck": true,
"noImplicitAny": false,
"paths": {
"@components/*": ["components/*"],
},
"@components/*": ["src/components/*"],
"@components": ["src/components"]
}
},
"include": [
"**/*"
@ -40,6 +42,6 @@
"exclude": [
"node_modules",
"dist",
"PRNameGenerator.ts",
"PRNameGenerator.ts"
]
}

View File

@ -7,28 +7,28 @@ import nodeExternals from 'webpack-node-externals';
import CssMinimizerPlugin from 'css-minimizer-webpack-plugin';
import TerserPlugin from 'terser-webpack-plugin';
import ESLintPlugin from 'eslint-webpack-plugin';
import { resolveTsAliases } from 'resolve-ts-aliases';
const dotEnvToParse = dotenv.config();
const libraryName = process.env.LIBRARY_NAME ? process.env.LIBRARY_NAME : "ui-library"
const externalCss = process.env.EXTERNAL_CSS === 'true' ? true : false
const externalCssName = process.env.EXTERNAL_CSS_NAME ? process.env.EXTERNAL_CSS_NAME : 'index.css'
const alias = resolveTsAliases(path.resolve('tsconfig.json'));
export default {
entry: './src/components/index.tsx',
externals: [nodeExternals()],
resolve: {
extensions: ['.js', '.jsx','.ts','.tsx', '.json'],
alias: {
'@components': path.resolve(__dirname, 'src/components/'),
}
alias,
},
mode: 'production',
output: {
filename: 'index.js',
path: path.resolve(__dirname, 'dist'),
library: libraryName,
library: libraryName,
libraryTarget: 'umd',
globalObject: 'this',
globalObject: 'this',
},
plugins: [
new CleanWebpackPlugin(),
@ -44,12 +44,6 @@ export default {
],
module: {
rules: [
{
test: /\.(tsx|ts)$/,
loader: "ts-loader",
exclude: /node_modules/,
options: { reportFiles: ['src/**/*.{ts,tsx}', '!src/**/*.stories.{ts,tsx}'] }
},
{
test: /\.(js|jsx|ts|tsx)$/,
exclude: /node_modules/,

80
webpack.cy.config.ts Normal file
View File

@ -0,0 +1,80 @@
import path from 'path';
import webpack from 'webpack';
import * as dotenv from 'dotenv';
import HtmlWebpackPlugin from 'html-webpack-plugin';
import MiniCssExtractPlugin from 'mini-css-extract-plugin';
import { CleanWebpackPlugin } from 'clean-webpack-plugin';
import CssMinimizerPlugin from 'css-minimizer-webpack-plugin';
import TerserPlugin from 'terser-webpack-plugin';
import ESLintPlugin from 'eslint-webpack-plugin';
import { resolveTsAliases } from 'resolve-ts-aliases';
const dotEnvToParse = dotenv.config();
const externalCss = process.env.EXTERNAL_CSS === 'true' ? true : false
const externalCssName = process.env.EXTERNAL_CSS_NAME ? process.env.EXTERNAL_CSS_NAME : 'index.css'
const alias = resolveTsAliases(path.resolve('tsconfig.json'));
export default {
entry: './src/components/index.tsx',
resolve: {
extensions: ['.js', '.jsx','.ts','.tsx', '.json'],
alias,
},
mode: 'development',
output: {
path: path.resolve(__dirname, 'dist'),
},
target: 'web',
plugins: [
new CleanWebpackPlugin(),
...(externalCss === true ? [
new MiniCssExtractPlugin({
filename: externalCssName,
}),
] : []),
new webpack.DefinePlugin({
'process.env': JSON.stringify(dotEnvToParse.parsed),
}),
new ESLintPlugin(),
new HtmlWebpackPlugin({
template: path.join(__dirname, 'public', 'index.html'),
}),
new webpack.ProvidePlugin({
React: 'react',
}),
],
module: {
rules: [
{
test: /\.(js|jsx|ts|tsx)$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
},
},
{
test: /\.(css|sass|scss)$/,
use: [
externalCss === true ? MiniCssExtractPlugin.loader : 'style-loader',
'css-loader',
'sass-loader',
],
},
{
test: /\.(ttf|otf|eot|woff|woff2)$/,
loader: 'url-loader',
options: {
name: 'assets/fonts/[name].[ext]',
esModule: false,
},
},
]
},
optimization: {
minimize: true,
minimizer: [
new CssMinimizerPlugin(),
new TerserPlugin(),
],
},
}