cypress get all arguments of mocked window open

Viewed 837

I mocked window.open in my cypress test as

cy.visit('url', {
        onBeforeLoad: (window) => {
            cy.stub(window, 'open');
        }
      });

in my application window.open is called as window.open(url,'_self')

I need to check cypress whether proper URL is opened or not

I need to fetch URL used and check if its match the regular expression or not

const match = newRegExp(`.*`,g)
cy.window().its('open').should('be.calledWithMatch', match); 

I'm getting error as


CypressError: Timed out retrying: expected open to have been called with arguments matching /.*/g

    The following calls were made:

    open("https://google.com", "_self") at open (https://localhost:3000/__cypress/runner/cypress_runner.js:59432:22)
1 Answers

I figured out how to do it. You need to capture the spy and then apply Chai assertions due to it's a Chai Spy

cy.window()
  .its('open')
  .then((fetchSpy) => {
    const firstCall = fetchSpy.getCall(0);    
    const [url, extraParams] = firstCall.args;

    expect(url).to.match(/anyStringForThisRegex$/i);
    expect(extraParams).to.have.nested.property('headers.Authorization');
    expect(extraParams?.headers?.Authorization).to.match(/^Bearer .*/);
  });

This is the way

Related