Cypress failed and wants to register "cy.task"

Viewed 1026

I have a problem with cy.task and I don't know what to do with it anymore. I'm trying to log in to Share Point using Cypress, but after running the test.js file I get a message that the "task" event has not been registered in the plugins file - \plugins\index.js

enter image description here

I enclose the contents of the files below.

\plugins\index.js:

/**
 * @type {Cypress.PluginConfig}
 */
// eslint-disable-next-line no-unused-vars
module.exports = (on, config) => {
  // `on` is used to hook into various events Cypress emits
  // `config` is the resolved Cypress config
}

'use strict'

const spauth = require('node-sp-auth');
const puppeteer = require('puppeteer');

/**
*
* @param {options.username} string username
* @param {options.password} string password
* @param {options.pageUrl} string URL of the SharePoint page
*/
module.exports.SharePointLogin = async function SharePointLogin(options = {}) {


  // Check if the required options are provided
  if (!options.username || !options.password) {
    throw new Error('Username or password missing.');
  }
  if (!options.pageUrl) {
    throw new Error('Login Url missing')
  }

  // Authenticate
  const data = await spauth.getAuth(options.pageUrl, {
    username: options.username,
    password: options.password
  });

  // Launch puppeteer to get the SP Headers
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  await page.setExtraHTTPHeaders(data.headers);
  await page.goto(options.pageUrl, {
    waitUntil: 'load'
  });

  // Retrieve the cookies from the browser session
  const cookies = await getCookies({ page, options });
  await finalizeSession({ page, browser, options });

  // Return the browser cookies
  return { cookies }
}

async function getCookies({ page, options } = {}) {
  // Wait for an element on the SharePoint page
  await page.waitForSelector("#SuiteNavPlaceHolder", { visible: true, delay: 10000 })
  // Retrieving all the cookies
  const cookies = options.getAllBrowserCookies
    ? await getCookiesForAllDomains(page)
    : await page.cookies(options.pageUrl)
  if (options.logs) {
    console.log(cookies)
  }
  return cookies
}

async function getCookiesForAllDomains(page) {
  const cookies = await page._client.send('Network.getAllCookies', {})
  return cookies.cookies
}

async function finalizeSession({ page, browser, options } = {}) {
  await browser.close()
}

commands.js:

Cypress.Commands.add('spAuth', function () {
    const options = {
        username: Cypress.env('username'),
        password: Cypress.env('password'),
        pageUrl: Cypress.env('appUrl')
    }

    cy.task('SharePointLogin', options).then(result => {
        cy.clearCookies();

        result.cookies.forEach(cookie => {
            cy.setCookie(cookie.name, cookie.value, {
                domain: cookie.domain,
                expiry: cookie.expires,
                httpOnly: cookie.httpOnly,
                path: cookie.path,
                secure: cookie.secure
            })
            Cypress.Cookies.preserveOnce(cookie.name)
        })
    })
});

and test.js:

describe('SharePoint SPFx Testing', function () {

    /**
     * Before visiting SharePoint, we first need to authenticate
     */
    before(function () {
        cy.spAuth();
    });

    /**
     * Check if the homepage can be opened
     */
    it('Can open the homepage', function () {
        cy.visit(`${Cypress.env('appUrl')}`);
    });

    /**
     * Validate what you want to validate
     */
    it('Validate if there are two images on the page', async () => {
        const elms = await cy.get('div[data-ui-test-id="brickheadz"] img');
        return expect(elms).to.be.length(2);
    });
})
2 Answers

Your task definition is not correct, see the docs page

module.exports.SharePointLogin = async function SharePointLogin(options = {}) {

should change to

module.exports = (on, config) => {
  on('task', {
    SharePointLogin(options = {}) {

      // ...function internals as above


      // Return the browser cookies
      return { cookies }
    },
  })
}

async function getCookies({ page, options } = {}) {
  ...
}

async function getCookiesForAllDomains(page) {
  ...
}

async function finalizeSession({ page, browser, options } = {}) {
  ...
}

The on('task', { ... part is the registering of the task that the error message refers to.

I put code which you told me, but there is some syntax error.

enter image description here

The problem seems to be with the constants - const:

  module.exports = (on, config) => {
on('task', {
  SharePointLogin(options = {}) {

    // Check if the required options are provided
    if (!options.username || !options.password) {
      throw new Error('Username or password missing.');
    }
    if (!options.pageUrl) {
      throw new Error('Login Url missing')
    }

    // Authenticate
    const data = await spauth.getAuth(options.pageUrl, {
      username: options.username,
      password: options.password
    });

    // Launch puppeteer to get the SP Headers
    const browser = await puppeteer.launch();
    const page = await browser.newPage();
    await page.setExtraHTTPHeaders(data.headers);
    await page.goto(options.pageUrl, {
      waitUntil: 'load'
    });

    // Retrieve the cookies from the browser session
    const cookies = await getCookies({ page, options });
    await finalizeSession({ page, browser, options });

    // Return the browser cookies
    return { cookies }
  },
})

}

Related