我正在尝试使用 Cypress 12.3 为 Web 应用程序编写 E2E 测试。在旅程的某个部分,应用程序向端点“ api/v2/accountApplication/getApplicationInfo?uuid=xxxxxxx ”发出GET请求。该请求的响应包括一个名为“ abChoice.welcome ”的字段,其值为“a”或“b”。该值用于我的 Vue 应用程序中的 A/B 测试。响应的结构如下:
{
    "resultStatus": true,
    "errorCode": 0,
    "errorMessage": null,
    "resultData": {
        "abChoice": {
            "welcome": "a"
        }
    }
}
我正在尝试编写一个测试来检查此请求的响应,并根据“abChoice.welcome”的值做出不同的断言。我尝试使用cy.intercept命令来检查响应,但它没有按预期工作。我还尝试为请求创建别名并使用cy.wait(@myAliasName),但 Cypress 抛出错误并表示从未发出请求,即使我可以在日志中看到该请求。
describe('A/B testing', () => {
  it('shows A or B pages', () => {
    cy.intercept('GET', '**/accountApplication/getApplicationInfo', req => {
      const { body } = req
      cy.log(body)
      if (body.resultData.abChoice.wlecome === 'a') {
        cy.log('A')
        // assert something
      } else {
        cy.log('B')
        // …我试图在 Cypress 中记录 API 响应时间,但找不到任何解决方案。使用什么,cy.intercept()或者cy.request()?
我试图使用这样的建议:
cy.intercept('POST', '**/create-insurance-view-model', (req) => {
                    const start = Date.now()
                    req.continue(res => {
                      res.responseTime = Date.now() - start;
                    })
                  }).as('apiViewModel')
cy.wait('@apiViewModel').then(intercept => {
                    cy.log(`Time to get the license plate data was: ${intercept.response.responseTime} seconds`)
                })
我在日志中变得未定义。
我对我的服务器进行了调用(是对 ibm watson 的调用)进行一些操作,如果一切正常,则返回 200 响应。
这个调用的时间超过 5000ms,cypress 可以等待。我需要等到服务器返回响应,然后我知道我的反应应用程序中会出现一个弹出窗口。
这是我从后端对 Watson 的调用:
const launchWatsonTest = (watsonData) => {     
  const data = {
    withCredentials: true,
    mode: 'cors',
     headers: {
      'x-access-token': watsonData.token,      
    }, 
    params: {
      topicId: watsonData.corpusNameId,
      workspaceId: watsonData.corpusArea
    }
  };      
  return clienteAxios.post(`test-watson`, watsonData, data);  
};
我该如何等待才能继续测试?
我对 cypress 进行了这个测试:
  describe("E2E CognitiveTool", function() {
    it("should crear respuesta simple sin problemas", function() {
      cy.visit("http://localhost:3000");
      cy.contains('[data-cy="topicName"]', 'CA2');   
      cy.get('[data-cy="accederResponsesCA2"]').click();
      cy.get('[data-cy="crearResponse"]').should('exist')
        .click();
      cy.get('input[name="description"]')
        .type('Simple Cypres Response');      
      cy.get('[name="typeResponse"]').first().check({force:true});
      cy.get('[name="lateral_W"]').first().check({force:true});
      cy.get('[name="rolViews"]').first().check({force:true});
      cy.get('[name="workLoadLevel"]').first().check({force:true});
      cy.get('[data-cy="continuar"]').click();
      cy.get('input[id=0]')
        .type('hola');
      cy.get('input[id=1]')
        .type('adios');
      cy.get('input[id=2]') …我只想在 Cypress 终端中记录消息,这样它们就不会出现在 Cypress 浏览器命令日志的屏幕截图中,而是可以在 CI 日志中查看。
我尝试使用Cypress.log(),但它将消息记录到终端和浏览器规范,这不是我想要的。这是我目前正在使用的,但它会用 RequestId 日志发送垃圾邮件屏幕截图(我只希望在 CI 终端中使用它)
beforeEach(() => {
  cy.intercept({ url: API_HOST + '/api/**', middleware: true }, req => {
    const requestId =
      // Apollo lower cases the headers before sending the request
      req.headers['x-request-id'] || req.headers['X-Request-Id'];
    if (requestId) {
       Cypress.log({
        name: 'RequestID:',
        message: requestId,
      });
    }
  });
});
我还尝试在 cy.intercept 中使用console.log(),但它仅记录到 Chrome 控制台而不是 Node.js 终端,因此消息不会显示在任何地方。(我注意到,如果我在其他地方的应用程序中使用 console.log ,它会将 console.log 添加到 Node.js 终端中,但特别是在 cy.intercept 中,它不会记录它)
最后,我尝试使用cy.task,
beforeEach(() => {
  cy.intercept({ …这是我的问题:我有一个大表单,我想在其中执行 e2e 测试。当用户更改其字段中的值时,此表单会填充 URL 查询参数。
当我使用 Cypress 来检查它时,每次在表单中输入内容时,它都会生成大量日志(例如(新 URL)见下文),使得测试难以阅读。
http://localhost:3000/demande-immersion?email=&firstName=Archib&lastName=&phone=&financiaryHelp=&emergencyContact=&emergencyContactPhone=&birthdate=&agencyDepartment=86&siret=&businessName=&businessAdvantages=&etFirstName=&etLastName=&etJob=&etPhone=&etEmail=&erFirstName=&erLastName=&erPhone=&erEmail=&immersionAddress=&agencyId=1411b4b7-a7a8-4d69-92ac-1eca1ac75c50&immersionActivities=&immersionSkills=&sanitaryPreventionDescription=&workConditions=&dateStart=2023-04-27&dateEnd=2023-04-28&schedule=%7B%22totalHours%22%3A14%2C%22workedDays%22%3A2%2C%22isSimple%22%3Atrue%2C%22selectedIndex%22%3A0%2C%22complexSchedule%22%3A%5B%7B%22date%22%3A%222023-04-27T00%3A00%3A00.000Z%22%2C%22timePeriods%22%3A%5B%7B%22start%22%3A%2208%3A00%22%2C%22end%22%3A%2212%3A00%22%7D%2C%7B%22start%22%3A%2213%3A00%22%2C%22end%22%3A%2216%3A00%22%7D%5D%7D%2C%7B%22date%22%3A%222023-04-28T00%3A00%3A00.000Z%22%2C%22timePeriods%22%3A%5B%7B%22start%22%3A%2208%3A00%22%2C%22end%22%3A%2212%3A00%22%7D%2C%7B%22start%22%3A%2213%3A00%22%2C%22end%22%3A%2216%3A00%22%7D%5D%7D%5D%7D
有没有办法过滤 Cypress 登录应用程序的事件(使用cypress open)?
我的测试将灯具存储在 cypress/fixtures 中,但 Cypress 无法找到它们。这是项目结构。我使用的是 cypress 12.14.0 版本
       __tests__
           cypress
              e2e
                mySpec.ts
           fixtures
              accounts.json
           support
              command.ts
              types.d.ts 
           tsconfig.ts
           cypress.config.ts
       __tests__
           cypress
              e2e
                mySpec.ts
           fixtures
              accounts.json
           support
              command.ts
              types.d.ts 
           tsconfig.ts
           cypress.config.ts
这是我尝试访问夹具的方法
     
         // tsconfig.js
         {
            "compilerOptions": {
            "target": "es5",
            "lib": ["dom", "dom.iterable", "esnext"],
            "allowJs": true,
            "skipLibCheck": true,
            "esModuleInterop": true,
            "allowSyntheticDefaultImports": true,
            "strict": true,
            "module": "esnext",
            "moduleResolution": "node",
            "resolveJsonModule": true,
            "isolatedModules": true,
            "noEmit": true,
            "types": ["cypress","./support"]
            },
             "include": ["/**/*cy.ts", "**/**/*.ts"]
           }
        
          
           //cypress.config.ts
            import { defineConfig } from "cypress";
            export default defineConfig({
                projectId: …在我的应用程序中,我需要在 cypress 中检查以下流程:
我尝试测试的第一件事很简单:
it('should display spinner during page load', () => {
    cy.visit(myPageUrl);
    cy.get(selectors.spinner).should('exist');
    cy.get(selectors.spinner, { timeout: 5000 }).should('not.exist');
});
然而,这会产生竞争条件。在 cypress 断言旋转器存在之前,页面可能会加载并且旋转器将消失。这是一个直观的解释:
这是我的预期: 预期结果
以下是实际可能发生的情况,这将导致测试失败: 可能的结果
因此,经过一番研究后,我尝试了以下方法来解决竞争条件:
it('should display spinner during page load', () => {
    
    let sendResponse;
    const trigger = new Promise((resolve) => {
        sendResponse = resolve;
    });
    cy.intercept('GET', '/myRequiredPageData', (req) => {
        return trigger.then(() => {
            req.reply();
        });
    });
    cy.visit(myPageUrl);
    cy.get(selectors.spinner).should('exist').then(() => {
        sendResponse();
        cy.get(selectors.spinner, { timeout: 5000 }).should('not.exist');
    });
});
但是,现在我有时会收到此错误:
A …
cypress ×7
e2e-testing ×1
end-to-end ×1
javascript ×1
react-redux ×1
response ×1
testing ×1
time ×1