Cypress: how to test webextension apis in cypress

Viewed 134

We have our extension installed on chrome browser which is launched by cypress. As url in the browser is one as per the list of integration tests(highlighted in red), unable to simulate webExtension apis like browser.tab.onUpdate or browser.webRequest etc. The selector playground doesnt support installing extension on it to test those events. For example listeners like this in the background script of our extensionenter image description here

  browser.webRequest.onBeforeRequest.addListener(
    (details) => {
      callback(details)
    },
    {
      urls: URLS_TO_MONITOR,
      types: ['main_frame'],
    }
  )

How can we simulate such events on browser launched by cypress ?

1 Answers

If you are running your tests in chrome, you can potentially use the Runtime.evaluate command in combination with the 'remote:debugger:protocol' in the automation:

Cypress.automation('remote:debugger:protocol', {command: 'Runtime.enable'});
cy.wrap(
  Cypress.automation('remote:debugger:protocol', {
    command: 'Runtime.evaluate',
    params: {
      expression: `new Promise((res,rej) => {
        res('my debug value')
      }) `,
      awaitPromise: true,
    },
  }),
).then(e => {
  cy.log(JSON.stringify(e));
});

You may be able to put your command in here. I am not an expert in this field and its almost undocumented, but I wanted to throw it out here, hoping it might help you. E.g

Cypress.automation('remote:debugger:protocol', {command: 'Runtime.enable'});
cy.wrap(
  Cypress.automation('remote:debugger:protocol', {
    command: 'Runtime.evaluate',
    params: {
      expression: `new Promise((res,rej) => {
          browser.webRequest.onBeforeRequest.addListener(
          (details) => {
            res(details)
          },
         {
           urls: URLS_TO_MONITOR,
           types: ['main_frame'],
         })
      }) `,
      awaitPromise: true,
    },
  }),
).then(e => {
  cy.log(JSON.stringify(e));
});
Related