javascript - 赛普拉斯夹具 - 类型错误:无法读取未定义的属性“travelData”
问题描述
出现错误Cypress test execution with fixture - "TypeError: Cannot read property 'travelData' of undefined"
以下是步骤:
1 - 创建一个travelData.json
文件并将其放入fixtures文件夹中:
{
"FIRSTNAME": "TESTTRAVEL",
"LASTNAME": "USER",
"MOBILE": "581234567",
"EMAIL": "test@test.com",
"PASSPORT": "AB1234",
"CURRENCY": "AED"
}
2 - 编写赛普拉斯测试并放入integration
文件夹中。代码如下:
context('Travel Portal Regression Test', () => {
beforeEach(function () {
cy.fixture('travel.testData').then((travelData) => {
this.travelData = travelData;
});
});
beforeEach(() => {
// cy.viewport('iphone-6')
cy.viewport(360, 640);
cy.visit('https://thoughtcoders.com/');
});
it('Testing ThoughtCoders Homepage', () => {
cy.log('Testing ThoughtCoders Homepage');
cy.log(this.travelData.FIRSTNAME);
});
});
当我运行 Cypress 测试时,我收到错误"TypeError: Cannot read property 'travelData' of undefined"。
请纠正我。
解决方案
看看Fixture Example Recipe,它展示了一种简单的方法,可以只加载一次fixture,并为规范中的每个测试保留它
beforeEach()
该模式是在 yourbefore()
和 current之间添加一个额外的beforeEach()
。
示例配方
context('loading once and using @', () => {
let city
let country
before(() => {
// load fixtures just once, need to store in
// closure variables because Mocha context is cleared
// before each test
cy.fixture('city').then((c) => {
city = c
})
cy.fixture('country').then((c) => {
country = c
})
})
beforeEach(() => {
// we can put data back into the empty Mocha context before each test
// by the time this callback executes, "before" hook has finished
cy.wrap(city).as('city')
cy.wrap(country).as('country')
})
it('has loaded fixtures', function () {
// again, the test has to use "function" callback
// to make sure "this" points at the Mocha context
expect(this.city).to.deep.equal({ name: 'Atlanta' })
expect(this.country).to.deep.equal({ name: 'United States' })
})
})
您需要的三个关键点是
- 使用闭包变量
- 使用 beforeEach() 在清除后“放回”变量
- 使用“function(){}”样式测试
在你的测试中
context('loading once and persisting the fixture', () => {
let travelData // key point #1
before(() => {
cy.fixture('travelData').then((data) => {
travelData = data;
});
})
beforeEach(() => { // key point #2
cy.wrap(travelData).as('travelData')
})
beforeEach(() => {
cy.viewport(360, 640);
cy.visit('https://thoughtcoders.com/');
});
it('Testing ThoughtCoders Homepage', function () { // key point #3
expect(this.travelData."FIRSTNAME").to.equal("TESTTRAVEL") // passes
})
})
推荐阅读
- git - 是以冒号为前缀的分支名称是 git push 的某种别名
- 删除 ? - javascript - 将 SCSS“导出”变量导入 .vue 文件中的 Javascript 代码,该文件由 vue-loader 加载并由 webpack 捆绑
- twitter-bootstrap - 忽略“数据放置”属性的引导工具提示
- oracle - 为变量赋值并调用多个命令
- python - librosa.load:加载文件时找不到文件错误
- angularjs - AngularJS在localStorage中获取新数据时调用方法
- jmeter - 如何在运行负载测试之前使用 Jmeter 创建活动会话
- ios - MKLocalSearch 结果不会返回多个匹配项
- javascript - 当我选择一个时如何折叠列表 #1
- 来自列表 #2 还是列表 #3?
- python - 如何使用 mysql 数据库中的元组构建一系列 pyqt5 按钮?