Ken
Ken

Reputation: 455

Get component variable value of a public variable not visible in the dom

I have an Angular component I am testing. I am trying see how the components public variable value changes given different interaction with the DOM.

The component itself is very complicated But I have a stripped down example

export class AgePricingComponent{
   pricing = new Pricing();

   onClick() {
      pricing.amount = 5;
   }
}

In my test I want to test that pricing.amount = 5; so I use the following test:

  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);

    })
  });

The error I get is

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: ...

How can I check that value of my public pricing property?

Upvotes: 0

Views: 306

Answers (1)

Tiana
Tiana

Reputation: 196

Angular doesn't automatically add variables to window, in fact it tries to hide them to avoid polluting the global object.

You would need to explicitly add it yourself, if window.Cypress is present indicating the app is being tested.

export class AgePricingComponent{

   pricing = new Pricing();

   // only when Cypress is running
   if (window.Cypress) {
    window.pricing = pricing
  }

   onClick() {
      pricing.amount = 5;
   }
}

If you inject the Pricing class, you could also mock it during the test.

Upvotes: 1

Related Questions