使用Cypress实现Swagger接口自动化测试

2025-09-04阅读(578)评论(0)牵着狗狗看MM

苏州实时公交查询

在现代Web开发中,前后端分离已成为主流开发模式。Swagger作为流行的API文档工具,帮助团队更好地设计和维护API。而Cypress作为强大的端到端测试框架,不仅能测试前端UI,还能高效地进行API测试。本文将介绍如何使用Cypress对Swagger文档中的API进行自动化测试。

为什么选择Cypress进行API测试?

Cypress提供了许多优势:

  • 直观的API和调试体验

  • 自动等待和重试机制

  • 实时重新加载测试

  • 简单的设置和配置

  • 能够同时测试前端和API

cypress的安装和使用这里就不赘述了
直接步入主题

1.获取Swagger文档的JSON并配置到cypress环境变量中

注意:这里如果在xx.cy.ts中通过接口去获取到的swagger Json数据,只能放在一个it中,也就是说不能为每个接口都生成一个case

如果要动态生成多个it,则需前置获取,也就是说xx.cy.ts只能获取静态变量

cypress.config.ts中配置如下代码

import { defineConfig } from 'cypress'
import syncFetch from 'sync-fetch'

export default defineConfig({
    reporter: 'cypress-mochawesome-reporter',
    video: true, //报告生成操作视频
    videoCompression: false, //压缩视频
    videosFolder: 'cypress/reports/videos',
    reporterOptions: {
        reportDir: 'cypress/reports', // 报告存放目录
        overwrite: false, // 不覆盖已有报告
        html: true, // 生成 HTML
        charts: true, // 报告中显示图表
        embeddedScreenshots: true, // 将截图嵌入报告
        inlineAssets: true, // 内联 CSS/JS,报告更独立
        json: false,
    },
    e2e: {
        supportFile: false, // 显式禁用支持文件
        viewportWidth: 1440, // 宽度
        viewportHeight: 900, // 高度
        specPattern: 'cypress/**/*.cy.ts', // 指定测试文件目录/规则
        setupNodeEvents(on, config) {
            require('cypress-mochawesome-reporter/plugin')(on)

           const apiUrl = 'http://yourswaggerUrl.com'

            const swaggerUrl = `${apiUrl}/v2/api-docs`
            const swaggerJson = syncFetch(swaggerUrl).json()//用sync-fetch获取JSON ,注意这里的URL是获取JSON文件的地址
            config.env.swaggerJson = swaggerJson//再添加到cypress的环境变量中
            config.env.apiUrl = apiUrl


            return config
        },
    },
})

 

2.为每个接口生成it

cypress/interration/api.cy.ts
// cypress/interration/api.cy.ts
import { handleParameters, filterParameters } from '../util'
import qs from 'qs'
const swaggerJson = Cypress.env('swaggerJson')
const apiUrl = Cypress.env('apiUrl')

describe('Swagger API Tests', () => {
    Object.entries(swaggerJson.paths || {}).forEach(
        ([path, methods], index) => {
            // if (index > 0) {
            //     return
            // }
            Object.keys(methods || {}).forEach((method) => {
                if (path === '/common/health') return
                let params: any
                if (method === 'get') {
                    //get请求, 过滤traceId,且没有x-exampl的,x-exampl即为后端的mock 请求参数内容
                    const parameters = filterParameters(
                        swaggerJson.paths[path]?.get.parameters,
                    )
                    if (parameters.length > 0) {
                        params = handleParameters(parameters)
                    }
                } else if (
                    method === 'post' &&
                    swaggerJson.paths[path]?.post.parameters
                ) {
                    //post请求
                    const parameters = filterParameters(
                        swaggerJson.paths[path]?.post.parameters,
                    )
                    if (parameters.length > 0) {
                        params = handleParameters(parameters)
                    }
                }

                it(`${method.toUpperCase()} ${path}   入参:${
                    params !== undefined ? JSON.stringify(params) : ''
                }`, () => {
                    cy.request({
                        method: method.toUpperCase(),
                        url: `${apiUrl}${path}`,
                        body: method === 'GET' ? qs.stringify(params) : params,
                        failOnStatusCode: false,
                    }).then((res: any) => {
                    
                        expect(res.status).to.be.oneOf([200, 400, 401, 403])
                        expect(res.body).to.have.property('code')
                        expect(res.body).to.have.property('msg')
                    })
                })
            })
        },
    )
})

 

赞(0)
转载请注明来源:Web前端(W3Cways.com) - Web前端学习之路 » 使用Cypress实现Swagger接口自动化测试
分享到: 更多 (0)