pactflow / pact-cypress-adapter

Cypress Pact Plugin
MIT License
25 stars 13 forks source link

No way to set provider state #16

Open CassianoSF opened 2 years ago

CassianoSF commented 2 years ago

Can you add an interface to pass a providerState id in pact files? It would be very helpful for me, I'm trying to use it with graphql, and I've made a lot of progress, this is the only feature missing for my use case so far.

This is the custom cypress command I'm using:

Cypress.Commands.add('stubRequest', ({ request, response, alias }) => {
  const previousInteceptions = Cypress.config('interceptions');

  const expectedKey = hash(
    JSON.parse(
      JSON.stringify({
        query: cleanQuery(getGqlString(request.query)),
        variables: request.variables,
      }),
    ),
  );

  Cypress.config('interceptions', {
    ...(previousInteceptions || {}),
    [expectedKey]: { alias, response },
  });

  if (previousInteceptions) return;

  cy.intercept('POST', 'http://localhost:4000/graphql', (req) => {
    const interceptions = Cypress.config('interceptions');

    const receivedKey = hash(
      JSON.parse(
        JSON.stringify({
          query: cleanQuery(req.body.query),
          variables: { ...req.body.variables },
        }),
      ),
    );

    const match = interceptions[receivedKey];
    if (match) {
      req.alias = match.alias;
      req.reply({ body: match.response });
    }
  });
});

With this I can stub exact request/responses 🙂

    cy.stubRequest({
      request: requestQueryUsersSeccess,
      response: queryUsersSuccess,
      alias: 'QUERY_USERS_SUCCESS',
    });
    cy.stubRequest({
      request: requestCreateUserSuccess,
      response: mutationCreateUserSuccess,
      alias: 'MUTATION_CREATE_USER_SUCCESS',
    });

If it was possible to add an providerState into this stubRequest command, it would be perfect!

YOU54F commented 2 years ago

Happy to consider a PR if you are willing