CI/CD自动化:GitHub Actions部署静态站点、Docker容器化构建测试策略:Jest单元测试、Cypress组件测试、Playwright端到端测试可视化与图形技术
·
GitHub Actions 部署静态站点
静态站点部署可以通过 GitHub Actions 实现自动化。以下是一个典型的 main.yml 配置文件示例,用于构建并部署静态站点到 GitHub Pages:
name: Deploy Static Site
on:
push:
branches: [ main ]
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- run: npm install && npm run build
- uses: peaceiris/actions-gh-pages@v3
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
publish_dir: ./dist
此工作流在每次推送到 main 分支时触发,安装依赖后执行构建命令,并将构建产物部署到 GitHub Pages。
Docker 容器化构建
前端应用可以通过 Docker 进行容器化。以下是一个多阶段构建的 Dockerfile 示例:
# 构建阶段
FROM node:18 as builder
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build
# 生产阶段
FROM nginx:alpine
COPY --from=builder /app/dist /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
此配置首先使用 Node.js 镜像构建应用,然后将构建产物复制到轻量级的 Nginx 镜像中。
Jest 单元测试策略
Jest 是流行的 JavaScript 测试框架。配置示例:
// jest.config.js
module.exports = {
testEnvironment: 'jsdom',
setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
moduleNameMapper: {
'\\.(css|less)$': 'identity-obj-proxy'
}
};
测试文件示例:
// sum.test.js
function sum(a, b) {
return a + b;
}
test('adds 1 + 2 to equal 3', () => {
expect(sum(1, 2)).toBe(3);
});
Cypress 组件测试
Cypress 适合组件测试。配置示例:
// cypress.config.js
const { defineConfig } = require('cypress');
module.exports = defineConfig({
component: {
devServer: {
framework: 'react',
bundler: 'vite'
}
}
});
测试文件示例:
// Button.cy.js
import React from 'react';
import { mount } from '@cypress/react';
import Button from './Button';
it('renders button with text', () => {
mount(<Button>Click me</Button>);
cy.contains('button', 'Click me').should('be.visible');
});
Playwright 端到端测试
Playwright 适合跨浏览器端到端测试。配置示例:
// playwright.config.js
const { defineConfig, devices } = require('@playwright/test');
module.exports = defineConfig({
testDir: './tests',
fullyParallel: true,
reporter: 'html',
use: {
baseURL: 'http://localhost:3000',
trace: 'on-first-retry'
},
projects: [
{
name: 'chromium',
use: { ...devices['Desktop Chrome'] }
}
]
});
测试文件示例:
// example.spec.js
const { test, expect } = require('@playwright/test');
test('has title', async ({ page }) => {
await page.goto('/');
await expect(page).toHaveTitle(/My App/);
});
可视化与图形技术实现
使用 Canvas API 绘制简单图形的示例:
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
ctx.fillStyle = 'blue';
ctx.fillRect(10, 10, 100, 100);
ctx.beginPath();
ctx.arc(200, 75, 50, 0, Math.PI * 2);
ctx.stroke();
使用 D3.js 创建数据可视化:
import * as d3 from 'd3';
const data = [4, 8, 15, 16, 23, 42];
const svg = d3.select('body').append('svg')
.attr('width', 500)
.attr('height', 300);
svg.selectAll('rect')
.data(data)
.enter()
.append('rect')
.attr('x', (d, i) => i * 70)
.attr('y', d => 300 - d * 5)
.attr('width', 65)
.attr('height', d => d * 5)
.attr('fill', 'steelblue');
更多推荐



所有评论(0)