尝试访问 this () 上下文上的别名值,我按照https://docs.cypress.io/api/commands/as#Fixture中的文档进行操作
在 .then 回调中,dataExample 参数已填充正常,但在 this.example 上它是未定义的。
describe('cy.as and this', function () {
it('Testing cy.as and this', function () {
cy.fixture('example.json').as('example')
.then(function (dataExample) {
cy.log('ACCESSING this, dataExample', this, dataExample);
});
cy.log(`ACCESSING this.example : ${JSON.stringify(this['example'])}`, this);
});
});
Run Code Online (Sandbox Code Playgroud)
第一个日志输出以下内容: dataExample 已正确填充,但 contex.example 未定义

.then 之外的第二个日志, this.example 也未定义

如果我将 cy.fixture 行移到 beforeEach() 中,它就会起作用。冷有人解释一下这种行为吗?
describe('alias', () => {
beforeEach(() => {
cy.fixture('example.json').as('example');
});
it('can access all aliases as properties', function () {
expect(this['example']).not.to.eq(undefined); // true
cy.log('THIS', this); // curious => [0]: Context {_runnable: undefined, test: undefined, example: undefined}
cy.log('THIS.example', this['example']); // {name: 'Using fixtures to represent data', email: 'hello@cypress.io',
// body: 'Fixtures are a great way to mock data for responses to routes'}
});
});
Run Code Online (Sandbox Code Playgroud)
考虑流程的一个有用方法是有两个过程:
第一遍,运行测试的 javascript 并执行普通 JS,但将Cypress 命令(及其回调)排入队列
第二遍执行这些命令
所以当
cy.log(`ACCESSING this.example : ${JSON.stringify(this['example'])}`, this)
Run Code Online (Sandbox Code Playgroud)
在第一遍中排队,this['example']立即评估参数(值是undefined)。
它没有存储要在第二遍中计算的参数表达式,这是大多数人所期望的。
但是您可以通过将参数放入另一个回调中来推迟参数评估。
cy.then(() => {
// this callback code is enqueued
// so the evaluation of "this['example']" is deferred until the queue is running
cy.log(`ACCESSING this.example : ${JSON.stringify(this['example'])}`, this)
})
Run Code Online (Sandbox Code Playgroud)
Gleb Bahmutov 有一篇博客
如何用不太令人困惑的 cy.later 命令替换令人困惑的 cy.then 命令
| 归档时间: |
|
| 查看次数: |
145 次 |
| 最近记录: |