Cypress Fixtures
cy.fixture() — 加载测试数据
// cypress/fixtures/user.json
{
"id": 1,
"name": "张三",
"email": "[email protected]",
"role": "admin"
}
cy.fixture('user').then(user => {
cy.get('#name').should('have.text', user.name);
});
// 别名复用
cy.fixture('user').as('userData');
// beforeEach 中加载
beforeEach(function () {
cy.fixture('user').as('user');
});
it('显示用户名', function () {
expect(this.user.name).to.equal('张三');
cy.visit('/profile');
cy.get('h1').should('have.text', this.user.name);
});
intercept 与 Fixtures 结合
cy.intercept('GET', '/api/users', { fixture: 'users.json' }).as('getUsers');
cy.intercept('GET', '/api/products', { fixture: 'products/list.json' });
cy.intercept('GET', '/api/users', {
statusCode: 200,
fixture: 'users.json',
headers: { 'x-total-count': '42' },
});
// 动态 fixture
cy.intercept('GET', '/api/users/*', (req) => {
const userId = req.url.split('/').pop();
req.reply({ fixture: `users/${userId}.json` });
});
动态 Fixture 数据
cy.fixture('user').then(user => {
const adminUser = { ...user, role: 'superadmin', active: true };
cy.intercept('GET', '/api/me', adminUser);
cy.visit('/dashboard');
cy.get('[data-cy="role"]').should('have.text', 'superadmin');
});
// 基于模板批量生成
cy.fixture('user').then(template => {
const users = Array.from({ length: 5 }, (_, i) => ({
...template,
id: i + 1,
name: `用户 ${i + 1}`,
}));
cy.intercept('GET', '/api/users', users);
});
工厂模式
// cypress/support/factories.ts
export function makeUser(overrides = {}) {
return {
id: Math.random(),
name: '测试用户',
email: '[email protected]',
role: 'viewer',
...overrides,
};
}
// 测试中使用
import { makeUser } from '../support/factories';
it('管理员可以审批订单', () => {
const admin = makeUser({ role: 'admin' });
cy.intercept('GET', '/api/me', admin);
cy.visit('/orders/1');
cy.get('[data-cy="approve-btn"]').should('be.visible');
});
Fixtures 最佳实践
| 实践 | 原因 |
|---|---|
使用 data-cy 属性 | 与 CSS/结构变更解耦 |
| 保持 fixtures 精简 | 只包含测试所需字段 |
| 用工厂函数生成变体 | 避免重复 fixture 文件 |
| 描述性命名 | user-admin.json 优于 data1.json |
| 在 beforeEach 中设置别名 | 用 this.fixtureName 访问 |