首页 > 解决方案 > 是否可以运行 cy.writeFile 或 cy.readFile 命令作为 cy.route 操作的一部分?

问题描述

我目前正在尝试使用赛普拉斯模拟客户端服务器响应模式。

我想:

  1. 当我单击“保存”按钮时,使用 cy.route 捕捉设置数据的调用
  2. 使用我的 cy.route 的 onResponse 参数将响应写入文件
  3. 使用文件的内容作为我对同一个 cy.route 调用的响应

目前,如果我包含 cy.writeFile 甚至是 console.log(cy.readFile(testFile)) 命令,当我使用 cy.wait 调用路由时会出现错误。

错误:

application_actions.js:84 Uncaught (in promise) TypeError: Cannot read property 'statusText' of undefined

如果我从 onResponse 块中删除 cy.writeFile 或 readFile ,则代码执行良好。

这是我正在做的一个例子:

beforeEach(() => {
      //call fixture file 
      cy.fixture('newApplication.json').as('newApplication')
      cy.server()
      //This first route is used when I load a page that contains application data. 
      //This works fine
      cy.route('GET', 'applications/*', '@newApplication').as('getNewApplication')
      //This route is hit when I click a Save Button to save updates to my application data
      cy.route({
        method: 'PATCH', 
        url: 'applications/update/*',
        onRequest: (xhr) => {
          cy.writeFile('cypress/fixtures/newApplication.json', xhr.request.body.application)
          },
        response: '@newApplication'
      })
      .as('updatedApplication')
      cy.visit('/admin/review_application/1')
      cy.wait('@getNewApplication')
      .its('response.headers')
      .its('content-type')
      .should('contain','application/json')
    });

it.only('Saving Restaurant Name changes page header text', () => {
      //Alter some application data
      cy.get('#Restaurant\\ Name')
        .clear()
        .type('Header Update Test');
      cy.get('#name-buttons\\ Accept').click();
      //Click save button to save data change
      clickSaveButton();
      //hit updatedApplication route when data is saved
      cy.wait('@updatedApplication').should('have.property','status',200)
      //Test fails on above wait every time
      cy.reload();
      cy.wait('@getNewApplication')
      cy.get('#Restaurant\\ Name').then($newText => {
          //compare text values to ensure the data change was saved
          cy.get('.MuiTypography-h2').then($headerText => {
          expect($headerText).to.have.text($newText.prop('value'));
        });
      });

似乎 cy.route 是完全同步的,所以也许这是不可能的,或者我做错了什么。

任何帮助,将不胜感激!

标签: javascriptpromiseroutescypress

解决方案


我无法让 cypress 写入同一个夹具文件,然后读回更改后的数据。即使我添加了第二个 cy.fixure 调用来尝试拉入修改后的文件。

相反,我最终写入了一个新文件,然后设置了新的路径来读取它。

clickSaveButton(); cy.wait('@updatedApplication').then((xhr) => { cy.writeFile('cypress/fixtures/updatedApplication.json', xhr.request.body.application).then(() => { cy.fixture('updatedApplication.json').as('updatedApplication') cy.route('GET', 'applications/*', '@updatedApplication').as('getUpdatedApplication') }) }) cy.reload() cy.wait('@getUpdatedApplication')

感谢您帮助我来到这里!


推荐阅读