【问题标题】:Cypress - Typescript - How can i make my fixture variables global?Cypress - Typescript - 我怎样才能使我的夹具变量全局化?
【发布时间】:2020-08-07 11:51:41
【问题描述】:

对 Cypress/Typescript 等来说相当新,我想从我的夹具中获取一个值,并使其可用于“执行搜索并验证返回的标头是否正确”测试。但是我似乎无法从我的测试中访问该变量,任何帮助表示赞赏:

这是我的夹具中的值:

{
  "manufacturer": "Dyson",
  "product": "9kJ Hand Dryer"

}

这是我从夹具创建别名并尝试访问变量的代码,但我收到以下错误:找不到名称'manuTerm'

describe('scenario-one', () => {
beforeEach(() => {// I need these variables availabe to multiple tests
cy.fixture('manufacturer').as('manuTerm');
});

it ('perform search and verify returned header is correct', () => {
    const lp = new sourceElements();
    lp.enterSearchTerm(manuTerm.manufacturer);
    lp.verifySearchResult(manuTerm.manufacturer);
});
});

Current errors

manuTerm: any

【问题讨论】:

  • 您的 JSON 文件是在 fixtures 文件夹内的根目录还是在 fixtures 文件夹内有一些子文件夹?
  • 它在根目录,没有子文件夹。当我使用别名时,我看到人们使用这种语法:lp.enterSearchTerm(this.manuTerm.manufacturer);即在夹具调用之前放置一个“this”,这也不起作用
  • 你是用this.manuTerm.manufacturer还是manuTerm.manufacturer,因为帖子里提到的sn-p代码没有this

标签: typescript cypress fixtures


【解决方案1】:

this 为我工作。但是您是否尝试过创建一个高变量?

describe('scenario-one', () => {
  let manu: any;
  before(() => {
    cy.fixture('manufacturer').then((val: any) => {
      manu = val;
    });
  });

  it('perform search and verify returned header is correct', () => {
    const lp = new sourceElements();
    lp.enterSearchTerm(manu.manufacturer);
    lp.verifySearchResult(manu.manufacturer);
  });
});

【讨论】:

    【解决方案2】:

    我认为这应该可行。

    describe('scenario-one', function() {
          beforeEach(() => { // I need these variables availabe to multiple tests
            cy.fixture('manufacturer').then(function(manuTerm:any) {
              this.manuTerm = manuTerm
              })
            })
    
            it('perform search and verify returned header is correct', () => {
              const lp = new sourceElements();
              lp.enterSearchTerm(this.manuTerm.manufacturer);
              lp.verifySearchResult(this.manuTerm.manufacturer);
            })
          })
    

    【讨论】:

    • 感谢您的回复,很遗憾您建议的代码不起作用。我之前曾尝试使用 'this.manuTerm.manufacturer' 语法,但没有成功。我现在有 2 个错误,但我并不真正理解它们:“包含箭头函数捕获了 'this' 的全局值。” '元素隐式具有'any'类型,因为类型'typeof globalThis'没有索引签名。'
    • @Sam2142 你能在这里张贴你的错误截图吗?我还从beforeEach describe 中删除了箭头,而是使用关键字function。你能试试这个吗?
    • 我添加了一个屏幕截图链接,显示我的代码(当前错误)和我遇到的 2 个错误。突出显示的代码有问题。如果我将您的“功能”而不是 => 添加到“执行搜索并验证返回的标头是否正确”测试中,我会收到另一个打字稿错误,例如 - 禁止使用此功能
    • @Sam2142 我已经更新了我的答案,介意现在试一试。我在beforeEach()中添加了manuTerm:any
    • 我已经添加了该语法,但它就像夹具数据一样在我的测试中不可用。我添加了另一个显示问题的屏幕截图。注意:如果我在测试本身中包含夹具调用,我可以访问夹具数据,但显然这不是最好的解决方案,因为我只想这样做一次,而不是在每个测试中......希望这是有道理的
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-26
    • 2022-06-10
    • 1970-01-01
    • 2019-10-30
    • 1970-01-01
    相关资源
    最近更新 更多