6

我正在尝试使用cypress来测试我构建的大型 Angular 应用程序。我的要求是我将一个期望文件加载到我的测试中,然后从这个期望文件中驱动测试。

到目前为止,我无法使用 、 的各种组合来实现它cy.readFile()cy.fixture()甚至axios无法通过 http 加载文件。

问题似乎是我不能在外面使用这些方法it(),如果我不能这样做,这意味着我不能遍历数据来创建它。我正在尝试做类似下面的事情......这在柏树中是否可能?我错过了一些明显的东西吗?

可以说我的期望是这样的:

{
    "mainPage": [1, 2, 3],
    "otherPage": [4, 5, 6]
}

我希望我的代码加载它并浏览各个页面:

describe(`Test the app `, function() {
    cy.readFile("path/to/expectation.json").then(function(expectation) {
        Object.keys(expectation).forEach(function(pageName) {
            it(`for page ${pageName}`, function() {
                gotoPage(pageName);
                var pageData = getDataFrompage();
                expect(pageData).to.equal(expectation[pageName]);
            })
        })
    })
})

在我看来,这似乎是一个非常明显的用例,所以我很困惑为什么它看起来如此困难:)

4

2 回答 2

3

我有类似的要求,除了我正在读取应用程序配置文件(位于应用程序资产文件夹中)。

我是require这样读的,

const runtimeConfig = require('../../../src/data/my-config');

这很好用,然后我可以根据文件内容继续进行测试。

所以,你的代码会是这样的

const expectation = require('path/to/expectation.json');

describe(`Test the app `, function() {
  Object.keys(expectation).forEach(function(pageName) {
    it(`for page ${pageName}`, function() {
      gotoPage(pageName);
      var pageData = getDataFrompage();
      expect(pageData).to.equal(expectation[pageName]);
    })
  })
})

读取文件()

尝试cy.readFile(),您会收到此错误消息

未捕获的错误:无法在运行测试之外调用“cy.readFile()”。

before您可以通过将读取包装成这样来停止此错误

let runtimeConfig;
before(function(){
  cy.readFile('./src/data/my-config.json').then( fileContents => {
    runtimeConfig = fileContents;
  })
})

但不幸的是,赛普拉斯在继续测试之前不会等待读取完成。


夹具()

我还尝试了example.spec.js中显示的夹具模式

context('Files', function(){
  beforeEach(function(){
    cy.visit('https://example.cypress.io/commands/files')
  })
  it('cy.fixture() - load a fixture', function(){
    // Instead of writing a response inline you can
    // connect a response with a fixture file
    // located in fixtures folder.

    cy.server()

    // https://on.cypress.io/fixture
    cy.fixture('example.json').as('comment')

    cy.route(/comments/, '@comment').as('getComment')

    // we have code that gets a comment when
    // the button is clicked in scripts.js
    cy.get('.fixture-btn').click()

    cy.wait('@getComment').its('responseBody')
      .should('have.property', 'name')
      .and('include', 'Using fixtures to represent data')

但即使将其复制到文件夹中,也无法使其与我的配置文件一起使用/cypress/fixtures

此外,这感觉很 hacky - 如果我正确理解这段代码,它会将读取的文件转换为伪路径导航,以便 Cypress 可以等待它。

这种模式很复杂,当然不适合您描述的动态测试场景。

于 2018-02-05T21:06:40.333 回答
0
  1. 假设,expectation.json 文件中有以下数据。
    {
      "mainPage": [1, 2, 3],
      "otherPage": [4, 5, 6]
    }
    

然后您的代码将是这样的,以动态创建测试用例

const data = require("path/to/expectation.json");

describe('Test the app', function() {
   Object.keys(data).forEach(function(page, i){
      it(`Test Case For: ${page}`, function() {
        cy.log(data[page])
      })
   })
})

请参阅下面的输出

于 2019-06-26T15:40:55.197 回答