cypress 获取模拟窗口打开的所有参数

que*_*nar 5 cypress

我在我的 cypress 测试中嘲笑 window.open 为

cy.visit('url', {
        onBeforeLoad: (window) => {
            cy.stub(window, 'open');
        }
      });
Run Code Online (Sandbox Code Playgroud)

在我的应用程序中 window.open 被称为window.open(url,'_self')

我需要检查 cypress 是否打开了正确的 URL

我需要获取使用的 URL 并检查它是否与正则表达式匹配

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

Run Code Online (Sandbox Code Playgroud)

我收到错误为


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)
Run Code Online (Sandbox Code Playgroud)

Jho*_*tan 4

我想出了怎么做。您需要捕获间谍,然后应用 Chai 断言,因为它是 Chai 间谍

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 .*/);
  });
Run Code Online (Sandbox Code Playgroud)

就是这样