如何在插件中暴露配置 schema 并校验?
解读
面试官想确认三件事:
- 你是否知道 Cypress 插件体系里“配置”到底从哪来、到哪去;
- 能否用官方推荐的 JSON Schema 把配置项的“名字、类型、默认值、是否必填”一次性描述清楚;
- 能否在插件加载阶段就把用户填错的配置拦下来,给出中文友好、可快速定位的报错,而不是等到测试运行时才炸掉。
国内团队普遍把插件抽成独立 npm 包供多条业务线复用,schema 校验一旦缺失,下游项目升级插件时极易因配置拼写错误导致流水线一夜全红,因此该考点既考察“规范意识”,也考察“工程化落地经验”。
知识点
- Cypress 插件入口:
cypress.config.js里的setupNodeEvents(on, config),插件通过config对象读取用户配置。 - 配置命名空间:插件必须把自己的配置挂到
config.env或config.[yourPluginName]下,避免与 Cypress 内置字段冲突。 - JSON Schema 2019-09 语法:
type、properties、required、additionalProperties、errorMessage(ajv-errors 扩展)等。 - ajv(Another JSON Validator)是 Node 端最快的主流校验器,支持异步校验与自定义关键字,国内镜像源安装无压力。
- 插件暴露方式:npm 包在
package.json中指明main: index.js,对外暴露defineConfig或plugin函数,返回{schema, preprocessor, task}等元信息。 - 校验时机:在
setupNodeEvents同步阶段完成校验,失败时通过throw new Error('[@your/plugin] xxxxx')直接阻断 Cypress 启动,错误信息会出现在控制台与cypress.log。 - 错误提示国际化:利用 ajv-i18n 包可输出中文错误,降低国内非英语背景开发者的排障门槛。
- 热更新安全:校验通过后再把冻结(Object.freeze)后的配置写回
config,防止运行时被意外篡改。
答案
- 在插件 npm 包中新建
schema.json:
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"apiBase": { "type": "string", "format": "uri" },
"timeout": { "type": "integer", "minimum": 1000, "default": 5000 },
"mock": { "type": "boolean", "default": false }
},
"required": ["apiBase"],
"additionalProperties": false,
"errorMessage": {
"properties": { "apiBase": "apiBase 必须是合法 uri,示例:https://api.xxx.com" }
}
}
- 在插件主文件
index.js里:
const Ajv = require('ajv');
const addFormats = require('ajv-formats');
const localize = require('ajv-i18n/localize/zh');
const schema = require('./schema.json');
const ajv = new Ajv({ allErrors: true, messages: false });
addFormats(ajv);
require('ajv-errors')(ajv);
function plugin(userOptions = {}) {
// 1. 校验
const valid = ajv.validate(schema, userOptions);
if (!valid) {
localize(ajv.errors); // 中文提示
const msg = ajv.errorsText(ajv.errors, { separator: '\n' });
throw new Error(`[@cypress/your-plugin] 配置校验失败:\n${msg}`);
}
// 2. 冻结,防止被其他插件篡改
const finalOpts = Object.freeze({ ...userOptions });
return (on, config) => {
// 把配置挂到 config.env 下供测试代码使用
config.env.yourPlugin = finalOpts;
// 注册任务、预处理等
};
}
module.exports = { plugin, schema }; // 暴露 schema 方便二次封装
- 用户在
cypress.config.js中调用:
const { defineConfig } = require('cypress');
const { plugin } = require('@cypress/your-plugin');
module.exports = defineConfig({
e2e: {
setupNodeEvents(on, config) {
plugin({
apiBase: 'https://api.xxx.com',
timeout: 3000
})(on, config);
return config;
}
}
});
若 apiBase 拼写错误或格式不对,Cypress 启动前即抛出中文堆栈,流水线秒级失败,开发者一眼定位。
拓展思考
- 动态 schema:若配置依赖环境变量,可在插件内先读
process.env.CYPRESS_xxx,再用ajv.compile动态生成 schema,实现“同包不同规”。 - IDE 智能提示:把 schema 转成 TypeScript 定义并发布
types.d.ts,国内 VS Code 用户即可获得自动补全与悬停校验,降低配置门槛。 - 可视化配置页:在中台项目里,可基于暴露的 schema 用
react-jsonschema-form自动生成配置页,运营人员无需写 JSON 就能完成插件参数下发。 - 版本兼容策略:利用
schema.version字段,插件内部维护配置迁移函数,当检测到旧配置时自动映射到新字段并打印console.warn,实现零中断升级。