首页 > 解决方案 > 在 Cypress 中重载自定义命令

问题描述

自定义命令重载可以像函数重载一样完成吗?文档中没有对此的答案。

例如:

Cypress.Commands.add('navigateAndWaitForApi', 
  (relativePath: string, apisPath: string[], timeout?: number) => {

    let options = {};
    if (timeout !== undefined) {
      options = { timeout: TIMEOUT };
    }
    apisPath.forEach((api)=> {
      cy.intercept(`/api/${api}`).as(api);  
    })
    cy.visit(`/${relativePath}`);
    cy.wait(apisPath.map(apiPath => `@${apiPath}`), options);
});


Cypress.Commands.add('navigateAndWaitForApi', 
  (relativePath: string, apiPath: string, timeout?: number) => {
    cy.navigateAndWaitForApi(relativePath, [apiPath], timeout);
});

标签: cypress

解决方案


事实并非如此。命令名称navigateAndWaitForApi是总签名。

在命令定义之后添加

console.log(Cypress.Commands._commands)

显示命令存储在一个对象中,由命令名称键入。

两次添加相同的命令,第二次覆盖第一个。


可以在运行时对参数进行类型检查。

Cypress.Commands.add('navigateAndWaitForApi', 
  (relativePath: string, apiPaths: string|string[], timeout?: number) => {

    if (typeof apiPaths === 'string') {
      apiPaths = [apiPaths]
    } 

    let options = {};
    if (timeout !== undefined) {
      options = { timeout: TIMEOUT };
    }
    apiPaths.forEach((api)=> {
      cy.intercept(`/api/${api}`).as(api);  
    })
    cy.visit(`/${relativePath}`);

    // cy.wait(apiPaths.map(apiPath => `@${apiPath}`), options);  // look dubious

    apiPaths.forEach(apiPath => {
      cy.wait(`@${apiPath}`), options)
    })

});

推荐阅读