用于动态测试的预扫描网页

发布于 2025-02-10 16:35:02 字数 767 浏览 1 评论 0原文

寻找对@JeffTanner提出的问题的确切答案在这里 生成动态测试。从这个问题和柏树样本中,很明显,我们需要在生成之前知道所需的测试数量。

问题

我们有一个网页,其中包含一个医疗分析数据表,白天多次刷新。每个刷新团队都必须检查数据,为了分配我们每行作为单独测试的工作。但是行的数量每次都会有所不同,这意味着我必须计算行并在每次运行中更新系统。寻找一种以编程方式获取行计数的方法。

html是< tbody>&lt> tr></tr></tbody>的表the each(),丢弃的错误是“找不到测试”

let rowCount;

beforeEach(() => {
  cy.visit('/analytics')
  cy.get('tbody tr').then($els => rowCount = $els.length)
})

Cypress._.times(rowCount => {
  it('process row', () => {
    ...
  })
})

Looking for a definitive answer to the question posed by @JeffTanner here about generating dynamic tests. From that question and the Cypress samples, it's clear that we need to know the number of tests required before generating them.

Problem

We have a web page containing a table of Healthcare analytic data that is refreshed many times during the day. Each refresh the team must check the data, and to divvy up the work we run each row as a separate test. But the number of rows varies every time which means I must count the rows and update the system on each run. Looking for a way to programmatically get the row count.

The HTML is a table of <tbody><tr></tr></tbody>, so the following is enough to get the count but I can't run it in a beforeEach(), the error thrown is "No tests found"

let rowCount;

beforeEach(() => {
  cy.visit('/analytics')
  cy.get('tbody tr').then($els => rowCount = $els.length)
})

Cypress._.times(rowCount => {
  it('process row', () => {
    ...
  })
})

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

寂寞美少年 2025-02-17 16:35:02

之前的:运行事件在测试开始之前触发,您可以在此处扫描网页。

setupnodeevents()中设置事件侦听器。柏树命令不会在这里运行,但是您可以使用等效的节点命令。

const { defineConfig } = require("cypress");

module.exports = defineConfig({
  e2e: {
    setupNodeEvents(on, config) {
      on('before:run', async (details) => {
        try {
          const fetch = require('node-fetch');
          const fs = require('fs-extra');
          const jsdom = require("jsdom");
          const { JSDOM } = jsdom;                           
          
          const response = await fetch(config.env.prescan);  // default below 
          const body = await response.text();                // or pass in command line

          const dom = new JSDOM(body);
          const rows = dom.window.document.body.querySelectorAll('tr')  // query

          // save results
          fs.writeJson('./cypress/fixtures/analytics-rows.json', {rows:rows.length})

        } catch (error) {
          console.log('error:', error)
        }
      })
    },
  },
  env: {
    prefetch: 'url-for-analytics-page'
  }
})

测试

import {rows} from './cypress/fixtures/analytics-rows.json'  // read row count

Cypress._.times(rows, (row) => {
  it(`tests row ${row}`, () => {
    ...
  })
}

The before:run event fires before the tests start, you can scan the web page there.

Set the event listener in setupNodeEvents(). Cypress commands won't run here, but you can use equivalent Node commands.

const { defineConfig } = require("cypress");

module.exports = defineConfig({
  e2e: {
    setupNodeEvents(on, config) {
      on('before:run', async (details) => {
        try {
          const fetch = require('node-fetch');
          const fs = require('fs-extra');
          const jsdom = require("jsdom");
          const { JSDOM } = jsdom;                           
          
          const response = await fetch(config.env.prescan);  // default below 
          const body = await response.text();                // or pass in command line

          const dom = new JSDOM(body);
          const rows = dom.window.document.body.querySelectorAll('tr')  // query

          // save results
          fs.writeJson('./cypress/fixtures/analytics-rows.json', {rows:rows.length})

        } catch (error) {
          console.log('error:', error)
        }
      })
    },
  },
  env: {
    prefetch: 'url-for-analytics-page'
  }
})

Test

import {rows} from './cypress/fixtures/analytics-rows.json'  // read row count

Cypress._.times(rows, (row) => {
  it(`tests row ${row}`, () => {
    ...
  })
}
握住你手 2025-02-17 16:35:02

一种可能性是在预测脚本中运行上述柏树测试,该脚本将始终在主测试脚本之前运行。

// package.json

{
  ...
  "scripts": {
    "pretest": "npx cypress run --spec cypress/e2e/pre-scan.cy.js",
    "test": "npx cypress run --spec cypress/e2e/main-test.cy.js",
  }
}
// pre-scan.cy.js

it('scans for table row count', () => {
  cy.visit('/analytics');
  cy.get('tbody tr').then($els => {
    const rowCount = $els.length;
    cy.writeFile('cypress/fixtures/rowcount.json', rowCount);
  });
});

One possibility is to run the above Cypress test in a pretest script which will always run before your main test script.

// package.json

{
  ...
  "scripts": {
    "pretest": "npx cypress run --spec cypress/e2e/pre-scan.cy.js",
    "test": "npx cypress run --spec cypress/e2e/main-test.cy.js",
  }
}
// pre-scan.cy.js

it('scans for table row count', () => {
  cy.visit('/analytics');
  cy.get('tbody tr').then($els => {
    const rowCount = $els.length;
    cy.writeFile('cypress/fixtures/rowcount.json', rowCount);
  });
});
季末如歌 2025-02-17 16:35:02

您可以将脚本scan-for-rows.js添加到project 脚本文件夹,

const rp = require('request-promise');
const $ = require('cheerio');
const fs = require('fs-extra');

rp('my-url')
  .then(function(html) {
    const rowCount = $('big > a', html).length
    fs.writeJson('row-count.json', {rowCount})
  })
  .catch(function(err){
    //handle error
  });

然后在package.json pre-pre-每当出现新版本的网页时,测试脚本。

You can add a script scan-for-rows.js to the project scripts folder, like this

const rp = require('request-promise');
const $ = require('cheerio');
const fs = require('fs-extra');

rp('my-url')
  .then(function(html) {
    const rowCount = $('big > a', html).length
    fs.writeJson('row-count.json', {rowCount})
  })
  .catch(function(err){
    //handle error
  });

Then in package.json call a pre-test script every time a new version of the web page appears.

离去的眼神 2025-02-17 16:35:02

这是一种在不使用其他软件包,插件,测试挂钩或NPM脚本的情况下将行计数获取的方法。

基本上,您可以创建一个单独的模块,该模块使用XMLHTTPRequest类制作同步的HTTP请求到/Analytics endpoint并使用浏览器的domparser class要查找返回&lt; tr&gt;标签的数字。

// scripts/get-row-count.js
export function getRowCount() {
  let request = new XMLHttpRequest();

  // Set async to false because Cypress will not wait for async functions to finish before looking for it() statements
  request.open('GET', '/analytics', false); 

  request.send(null);

  const document = new DOMParser().parseFromString(request.response, 'text/html');

  const trTags = Array.from(document.getElementsByTagName('tr'));

  return trTags.length;
};

然后在规格文件中导入新功能,现在您可以在需要时获得更新的行计数。

import { getRowCount } from '../scripts/get-row-count';

Cypress._.times(getRowCount() => {
  it('process row', () => {
    ...
  })
})

xmlhttprequest而不是获取的原因是因为它允许提出同步请求。需要同步请求,因为赛普拉斯不会等待异步请求在解析it()块之前返回。

这样,您始终拥有最新的排数量,而无需过时。

Here's a way to get the row count in the spec file without using extra packages, plugins, test hooks, or npm scripts.

Basically, you can create a separate module that makes a synchronous HTTP request using the XMLHTTPRequest class to the /analytics endpoint and use the browser's DOMParser class to find the return the number of <tr> tags.

// scripts/get-row-count.js
export function getRowCount() {
  let request = new XMLHttpRequest();

  // Set async to false because Cypress will not wait for async functions to finish before looking for it() statements
  request.open('GET', '/analytics', false); 

  request.send(null);

  const document = new DOMParser().parseFromString(request.response, 'text/html');

  const trTags = Array.from(document.getElementsByTagName('tr'));

  return trTags.length;
};

Then in the spec file, import the new function and now you can get an updated row count whenever you need it.

import { getRowCount } from '../scripts/get-row-count';

Cypress._.times(getRowCount() => {
  it('process row', () => {
    ...
  })
})

The reason for XMLHTTPRequest instead of fetch is because it allows synchronous requests to be made. Synchronous requests are needed because Cypress won't wait for async requests to come back before parsing for it() blocks.

With this, you always have the most up to date row count without it going stale.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文