Cypress 命令

导航与查询

cy.visit('/login'); cy.visit('https://example.com', { timeout: 10000 }); cy.get('#email'); cy.get('[data-cy="submit-btn"]'); cy.get('button').first(); cy.get('li').eq(2); cy.contains('提交'); cy.contains('button', '登录'); cy.url().should('include', '/dashboard'); cy.title().should('equal', '控制台');

操作 — click、type、select

cy.get('button').click(); cy.get('#email').type('user@example.com'); cy.get('#password').type('secret{enter}'); cy.get('#field').clear().type('新内容'); cy.get('select').select('选项二'); cy.get('[type="checkbox"]').check(); cy.get('[type="radio"]').check('value1'); cy.get('input[type="file"]').selectFile('cypress/fixtures/upload.pdf');

断言 — should / and

cy.get('.modal').should('exist'); cy.get('.modal').should('be.visible'); cy.get('#msg').should('contain.text', '成功'); cy.get('input').should('have.value', '张三'); cy.get('.btn').should('have.class', 'active'); cy.get('li').should('have.length', 5); cy.get('input') .should('be.visible') .and('have.attr', 'type', 'email');

cy.intercept — 网络拦截

cy.intercept('GET', '/api/users', { fixture: 'users.json' }).as('getUsers'); cy.intercept('POST', '/api/users', { statusCode: 201, body: { id: 99 } }); cy.visit('/'); cy.wait('@getUsers'); cy.get('@getUsers').its('response.statusCode').should('eq', 200);

自定义命令与别名

// cypress/support/commands.ts Cypress.Commands.add('login', (email, password) => { cy.request('POST', '/api/login', { email, password }) .its('body.token') .then(token => { window.localStorage.setItem('auth_token', token); }); }); // 使用 cy.login('admin@example.com', 'password'); cy.visit('/dashboard'); // 别名 cy.get('[data-cy="submit"]').as('submitBtn'); cy.get('@submitBtn').click();

命令速查表

命令用途
cy.visit(url)导航到 URL
cy.get(selector)查找元素
cy.contains(text)按文本内容查找
cy.type(text)输入文本
cy.should()断言
cy.intercept()mock/监听网络请求
cy.fixture()加载 fixture 数据