如何获取Angular组件中DOM不可见的公共变量值?
如何在Cypress中获取Angular组件的公共变量值?
我正在测试一个Angular组件,想要查看DOM交互后组件公共变量pricing的值变化情况。组件简化代码如下:
export class AgePricingComponent{ pricing = new Pricing(); onClick() { pricing.amount = 5; } }
为了验证pricing.amount是否被正确设置,我写了如下Cypress测试代码:
it('should set all of the age pricing', () => { cy.get('#age-amount-0').clear().type(-5); cy.get('#submit-btn').click(); cy.window().then((win)=>{ let pricing = win.pricing.amount; cy.log(pricing); expect(pricing.amount).equals(-5); }) });
但运行时出现错误:
TypeError: win.pricing is undefined
at ./cypress/e2e/admin/create-new-tournament.cy.js/</ (webpack:///./cypress/e2e/admin/create-new-tournament.cy.js:40:20)
at getRet (http://localhost:4200/__cypress/runner/cypress_runner.js:139235:20)
From previous event:
...
解决方法
Angular组件的属性默认不会挂载到全局window对象上,直接通过win.pricing自然无法访问。以下是几种可行的获取方式:
1. 临时将组件实例挂载到全局(适合调试)
在组件类中,仅在测试环境下把实例绑定到window对象,避免生产环境暴露内部变量:
export class AgePricingComponent{ pricing = new Pricing(); constructor() { if (window.Cypress) { window['AgePricingComponent'] = this; } } onClick() { this.pricing.amount = 5; } }
之后在Cypress测试中即可访问:
cy.window().then((win)=>{ const component = win.AgePricingComponent; expect(component.pricing.amount).to.equal(-5); });
2. 使用Cypress Angular插件(规范方案)
对于Angular项目,推荐使用@cypress/angular插件直接获取组件实例:
先安装插件:
npm install @cypress/angular --save-dev
然后在测试中通过cy.mount挂载并获取组件:
import { AgePricingComponent } from './path-to-your-component'; it('should set all of the age pricing', () => { let componentInstance; cy.mount(AgePricingComponent).then((mountResult) => { componentInstance = mountResult.component; }); cy.get('#age-amount-0').clear().type(-5); cy.get('#submit-btn').click(); expect(componentInstance.pricing.amount).to.equal(-5); });
3. 通过DOM元素间接验证(E2E测试最佳实践)
E2E测试更建议验证UI表现而非内部状态,若必须验证变量值,可以在组件模板中添加隐藏元素暴露值:
<span id="pricing-amount" style="display: none">{{ pricing.amount }}</span>
然后在测试中读取该元素的文本内容:
cy.get('#submit-btn').click(); cy.get('#pricing-amount').invoke('text').then((text) => { expect(parseInt(text)).to.equal(-5); });
内容的提问来源于stack exchange,提问作者Ken
相关产品推荐
相关产品推荐

