@civitas-cerebrum/context-store (英语)
用于管理测试状态和跨测试步骤的背景数据的轻量级、强型和框架不可知性用途.
在写入端到端(E2E)或集成测试时,您往往需要将一步中生成的数据(如动态ID,被取出的日期,或电子邮件地址)传递给后续步骤. context-store 将杂乱的平版 JavaScript 对象替换为基于强烈地图的 API, 提供安全的类型播报, 默认值, 以及干净的迭代 .
安装
npm i @civitas-cerebrum/context-store
为什么使用上下文存储器?
- 类型安全 : 内建的 TypeScript 支持可确保您准确知道您正在检索的数据 .
- 安全剖析 : 方法一样
getBoolean财务报告和审定财务报表getNumber优雅地处理缺失或有可靠倒计时的畸形数据. - 框架不可知性: 与Playwright, Cypress, WebdriverIO, Jest, Mocha, 或 Cucumber 完美合作.
- 清洁迭代 : 方便地通过存储的密钥值对循环进行批量断言.
快速启动
import { ContextStore } from '@civitas-cerebrum/context-store';
// Instantiate a new store for your test
const context = new ContextStore();
// Store data during a step
context.put('UserEmail', '[email protected]');
context.put('IsSubscribed', true);
context.put('RetryCount', '3'); // Note: Stored as a string
// Retrieve data safely in later steps
const email = context.get('UserEmail');
const isSubscribed = context.getBoolean('IsSubscribed');
const retries = context.getNumber('RetryCount', 0); // Safely parsed to a number!
console.log(email); // '[email protected]'
API 参考
| 方法 | 说明 | 示例 |
|---|---|---|
put(key, value) | 与特定的钥匙相关联 忽略无效/ 未定义输入 . | context.put('id', 123); |
get<T>(key, default?) | 获取一个值,如果缺少密钥,可选择返回默认值. | context.get<string>('name', 'N/A'); |
getBoolean(key, default?) | 回返 true 如果存储的值为布尔真值或字符串 "true"。 。 。 . | context.getBoolean('isActive', false); |
getNumber(key, default?) | 解析并返回数值为数字。 如果解析失败, 则返回默认值 . | context.getNumber('price', 0); |
has(key) | 回返 true 如果商店中包含指定的密钥. | context.has('token'); |
merge(...sources) | 将记录或其他地图中的属性合并到当前存储中. | context.merge({ a: 1, b: 2 }); |
entries() | 返回数组 [key, value] 配对,适合循环和断言. | for (const [k, v] of context.entries()) |
items() | 回返a Set 包含当前存储的所有密钥. | context.items(); |
remove(key) | 从商店中删除特定条目. | context.remove('temporaryId'); |
clear() | 清除商店的所有数据. | context.clear(); |
高级: Playwright 修复集成
而不是即兴表演 ContextStore 每一次测试中,可以手动使用Playwright Fixtures自动注入.
1. 界定固定位置(fixtures.ts:
import { test as base } from '@playwright/test';
import { ContextStore } from '@civitas-cerebrum/context-store';
type MyFixtures = {
context: ContextStore;
};
export const test = base.extend<MyFixtures>({
context: async ({}, use) => {
// Creates a fresh store for every test run
const store = new ContextStore();
await use(store);
},
});
2. 在测试中使用(example.spec.ts:
import { test } from './fixtures';
test('My test using the context store', async ({ page, context }) => {
await test.step('Generate Data', async () => {
context.put('orderId', 'ORD-999');
});
await test.step('Verify Data', async () => {
const orderId = context.get('orderId');
// Proceed with assertions...
});
});
许可证
麻省理工学院