tgriesser / cypress-graphql-mock

Adds commands for executing a mocked GraphQL server using only the client
171 stars 43 forks source link

Not possible to use graphql aliases in operations #7

Closed todda00 closed 5 years ago

todda00 commented 5 years ago

I have some queries which call the same field with different arguments and use an alias to remap the field names for the duplicate fields in the query. This behavior is not possible to replicate in cy.mockGraphqlOps({operations: {...}}).

See a potential query here:

query ChannelsQuery{
  me{
    _id
    canCreateChannels: hasPerm(entity:"channel" action:"create")
    canViewChannels: hasPerm(entity:"channel" action: "read")
  }
  ...
}

if I provide the operation value:

cy.mockGraphqlOps({
      operations: {
        ...baseOperations,
        ChannelsQuery: {
          me: {
            ...me,
            hasPerm: false,
          },
          ...
      }
   }
});

This will set canCreateChannels and canViewChannels both as false, but there is no way to set the alias values individually.

todda00 commented 5 years ago

The good news is this works using mocks at least. The mock resolver fields can access arguments, and return different results as needed.

cy.mockGraphql({
      schema: Cypress.env("GRAPHQL_SCHEMA"),
      endpoint: "/api",
      mocks: {
        RootQuery: () => ({
          me: () => ({
            __typename: "User",
            _id: "user_1",
            firstName: "Test",
            lastName: "User",
            shortName: "Test U.",
            hasPerm: (parent, args)=> {
              // logic to check arguments and return what is needed
              return true;
            }
          })
        })
      }
    }).as("mockGraphqlOps");
todda00 commented 5 years ago

Sorry for the noise, this method works as well for operations, for a while the alias name was tripping me up until I realized this is all the same as a resolver function, alias or not.

cy.mockGraphqlOps({
      operations: {
        ChannelsQuery: {
          me: {
            ...me,
            hasPerm: (parent, args)=> {
              // logic to check arguments and return what is needed
              return true;
            }
          },
          ...
      }
   }
});