Giter VIP home page Giter VIP logo

cypress-graphql-mock's People

Contributors

dmtrkovalenko avatar dvdvdmt avatar estrada9166 avatar haf avatar joefiorini avatar tgriesser avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

cypress-graphql-mock's Issues

Error: Currently only support fetch(url, options), saw fetch(Request)

I'm getting the following error when using cypress-graphql-mock with @apollo-client

It seems like it doesn't support the standard way @apollo-client makes fetch requests?

Please consider adding support for this.

I tried adding a very quick test myself to see how difficult it is to stub, but it seems straight forward? Even something as simple as this works:

  function fetchStub(path, request) {
    if (request && request.body) {
      // Using operation name of the request to look for response mock data
      const { operationName }  = JSON.parse(request.body)

Mock graphql HTTP OPTIONS request

Is it possible to mock an applications call to HTTP OPTIONS?

My application under test will fail to load if the calls to OPTIONS are dropped

[docs] difference in schema registration example<->README

Examples does:

import schema from '../../../schema.json';
// snip
  beforeEach(() => {
// snip
    cy.mockGraphql({ schema });

Docs do:

  cy.task("getSchema").then(schema => {
    cy.mockGraphql({
      schema,
      operations: { ... }
    });
  });

There's also a code-generator in the example and a command to update the schema json file. It's unclear:

Allow Access to makeExecutableSchema

I am getting the following warning:

Type "Entity" is missing a "__resolveType" resolver. Pass false into "resolverValidationOptions.requireResolversForResolveType" to disable this warning.

We don't have access to makeExecutableSchema to disable this warning:

const executableSchema = makeExecutableSchema({
  typeDefs,
  resolvers,
  resolverValidationOptions: {
    requireResolversForResolveType: false
  }
})

We also don't have access to resolvers to add a workaround:

const resolvers = {
  Query: {
    // …
  },
  Node: {
    __resolveType() {
      return null
    }
  }
}

I suggest that makeExecutableSchema should be configurable so that the schema can be configured contextually:

// src/index.ts
Cypress.Commands.add(
  "mockGraphql",
  <AllOperations extends Record<string, any>>(
    options: MockGraphQLOptions<AllOperations>
  ) => {
    const {
      endpoint = "/graphql",
      delay = 0,
      operations = {},
      mocks = {}
    } = options;

    const schema = makeExecutableSchema({
      typeDefs: schemaAsSDL(options.schema),
      ...(options.makeExecutableSchema || {})
    });
    
    // ...

Related: apollographql/apollo-server#1075

Please upgrade README

This plugin isn't working for angular apps because of apollo-angular-link-http is using xhr to fetching data. This plugin works only for apollo links which are using fetch (like this in react).

I guess this info should be included in the readme.

Cannot Handle Cusomt Scalars

I am importing my schema as one big json object and seeing this error when I try to run the command.

GraphQL error: No mock defined for type "DateTime"

To reproduce, add the custom DateTime scalar as a type to one of your properties.

Mock data always return "Hello World"

Hi guys, I'm quite new in GraphQL world and currently I'm facing some difficulties/trouble trying to implement this plugin, If anyone can help, I'll be really thankful .

Problem:

All my mock data fields are returning Hello World

How I'm using this plugin:

In my integration/index.spec.js

  context('Get email', () => {
      beforeEach(() => {
          cy.server();
          cy.mockGraphql({ schema });
          cy.mockGraphqlOps({
              operations: {
                GetEmail: {
                  email: "[email protected]",
                }
              }
          })
      });
      
        it('Should mock graphql', () => {
          cy.visit('/')
        })
  })

But I get

{
  GetEmail: {
    email: 'Hello World'
  }
}

Thanks guys ❤️

Intercept request

How can I intercept the stubbed fetch call to inspect the request body?

[docs] Document jsm usage: Can't reexport the named export 'BREAK'

./node_modules/graphql/index.mjs 42:0-48:205
Can't reexport the named export 'BREAK' from non EcmaScript module (only default export is available)
    at HarmonyExportImportedSpecifierDependency._getErrors (src/site/node_modules/webpack/lib/dependencies/HarmonyExportImportedSpecifierDependency.js:363:6)
    at HarmonyExportImportedSpecifierDependency.getErrors (src/site/node_modules/webpack/lib/dependencies/HarmonyExportImportedSpecifierDependency.js:343:16)
    at Compilation.reportDependencyErrorsAndWarnings (src/site/node_modules/webpack/lib/Compilation.js:1425:22)
    at hooks.finishModules.callAsync.err (src/site/node_modules/webpack/lib/Compilation.js:1221:10)
    at AsyncSeriesHook.eval [as callAsync] (eval at create (src/site/node_modules/tapable/lib/HookCodeFactory.js:33:10), <anonymous>:24:1)
    at AsyncSeriesHook.lazyCompileHook (src/site/node_modules/tapable/lib/Hook.js:154:20)
    at Compilation.finish (src/site/node_modules/webpack/lib/Compilation.js:1216:28)
    at hooks.make.callAsync.err (src/site/node_modules/webpack/lib/Compiler.js:662:17)
    at _err0 (eval at create (src/site/node_modules/tapable/lib/HookCodeFactory.js:33:10), <anonymous>:11:1)
    at _addModuleChain (src/site/node_modules/webpack/lib/Compilation.js:1148:12)
    at processModuleDependencies.err (src/site/node_modules/webpack/lib/Compilation.js:1060:9)
    at _combinedTickCallback (internal/process/next_tick.js:131:7)
    at process._tickCallback (internal/process/next_tick.js:180:9)
 @ ./node_modules/cypress-graphql-mock/dist/index.js
 @ ./cypress/support/commands.js
 @ ./cypress/support/index.js
 @ multi ./cypress/support/index.js

When following the readme; 1) install, 2) add import to commands.js, 3) save a .ts test file.

ERR_EMPTY_RESPONSE

when trying to make a request I get a ERR_EMPTY_RESPONSE from the fetch call.

cy.get() could not find a registered alias for: @mockGraphqlOps.

version:0.3.1

This is the code in use.
integration/login.js:

const schema = require('../../schema.json')
context('login', () => {
    beforeEach(() => {
        cy.mockGraphql({
            schema: schema,
            endpoint: "/api/task",
        })
        cy.mockGraphqlOps({
            operations: {
                userLogin: {
                    userLogin: {
                        token: "7b278a718dd147dd912f9d542540bd09",
                        userId: 1080,
                        orgId: 1013,
                        name: "账务",
                        avatar: "",
                        needInitOrg: false,
                        __typename: "UserLoginResp"
                    }
                },
                getUserInfo: {
                    personalInfo: {
                        data: {
                            user: {
                                id: 1080,
                                loginName: "18891111112",
                                name: "张三三",
                                sex: 99,
                                email: "",
                                avatar: "",
                                level: 1,
                                levelName: "试用级别",
                                rimanente: 10,
                                emplId: "",
                                orgId: 1013,
                                orgName: "星星电灯水水水水",
                                orgCode: "",
                                mobile: "18891111112",
                                thirdName: "",
                                birthday: "1970-01-01 00:00:00",
                                passwordSet: 1,
                                isAdmin: false,
                                remindBindPhone: 2,
                                functions: [],
                                __typename: "PersonalInfo"
                            }
                        }
                    }
                }
            }
        });
    })
})

This is the code in use.
support/command.js:

import "cypress-graphql-mock";

This is the brower result:
3404D608-D21B-431a-AD4F-92302D5B20C0

Expected { __schema:[snip] } to be a GraphQL schema.

When following the getting started example and registering an op, you get this error:

"Expected { __schema: { queryType: [Object], mutationType: [Object], subscriptionType: [Object], types: [Array], directives: [Array] } } to be a GraphQL schema."

Seemingly from this plugin. This is the code in use:

/// <reference types="Cypress" />
import schema from '../../../schema.json'

context("app inbox", () => {
  before(() => {
    cy.request('POST', '/api/accounts/seed', { failOnStatusCode: true })
  })

  beforeEach(() => {
    cy.server()
    cy.mockGraphql({
      schema
    })
  })

  it("shows", () => {
    cy.url().should('include', '/app/inbox')
  })

  it.only('renders inbox items', () => {
    cy.mockGraphqlOps({
      operations: {
        fetchInboxItems: {
          inbox: [ {
            __typename: 'Notice',
            id: '123',
            urgency: 'urgent',
            importance: 'important',
            title: "Testing",
            description: 'Testing desc'
          } ]
        }
      }
    })
    cy.visit('/app/inbox')
    cy.log('using schema', schema)
  })
})

Which results in this inside Cypress/the app:

Screenshot 2019-09-04 at 12 31 11

Screenshot 2019-09-04 at 12 32 22

And the error property in the Apollo client being a non-null, non-undefined value, with the same error string.

The schema.json is being fetched with, before running the tests:

apollo schema:download --endpoint=http://127.0.0.1:3000/graphql

stop using cy.task

with cy.task you can't pass mocks as functions

this works really well for me:

import { makeExecutableSchema, addMockFunctionsToSchema } from 'graphql-tools';
import { print } from 'graphql/language/printer';
import { graphql } from 'graphql';

Cypress.Commands.add(
  'graphql',
  ({ query, resolvers, mocks, preserveResolvers = true }) =>
      cy.readFile('schema.graphql').then(typeDefs => {
        const schema = makeExecutableSchema({
          typeDefs,
          resolvers,
        });

        addMockFunctionsToSchema({
          schema,
          mocks,
          preserveResolvers,
        });

        return graphql(schema, print(query)).then(value => {
          console.dir({ value }, { depth: Infinity });
          return value;
        });
      })
);

however I don't know how to mock cy.route for multiple requests since its the same URL

Not possible to use graphql aliases in operations

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.

Multi GQL endpoint options

Our ApolloClient receives two parallel GQL endpoints and our queries are resolving to them.

Tried to provide endpoint for multiple mockGraphql methods or defining on a task, but so far no luck with it.

Do you have any suggestion to approach this, with a maintainable manner?

Importing cypress-graphql-mock stops custom methods from being defined

From using the typescript example recipe, adding the import statement for cypress-graphql-mock breaks the registration of new methods. File: https://github.com/cypress-io/cypress-example-recipes/blob/master/examples/preprocessors__typescript-webpack/cypress/support/commands.ts

I'm not able to use this module due to this feature being disabled. Rather than doing all of the cypress type registration and method adding in the imported file, this module could expose the type definitions and methods so that they can be bound in a declare namespace statement as per the recipe

Edit:

The commands.ts supplied in the example by cypress is an internal module, to work together with cypress-graphql-mock you need to move the commands.ts file elsewhere to allow it to remain as an internal module, and create a new commands.ts file which imports both cypress-graphql-mock and the moved commands.ts

// commands.ts
import 'cypress-graphql-mock';
import './custom-commands';

Maybe this should be noted in the read me for typescript users

Improve docs to add "graphql-tools" better examples

Hey guys,

Do you think it worths adding more examples on README regarding the integration with graphql-tools? It took some time to me to understand how to add my custom scalars on mockGraphql, even though it is pretty straightforward I had to took a look at the source to have a clear understanding on it. :)

Examples using fs.readFileSync

Are there any examples of using this plugin with fs.readFileSync? I'd prefer to read in the graphql schema than import a json introspection query.

Have to specify .as() alias when setting an endpoint

When specifying an endpoint, an error is produced:

beforeEach(() => {
    cy.server();
    cy.mockGraphql({
      schema: Cypress.env("GRAPHQL_SCHEMA"),
      endpoint: "/api"
    });
  });

produces error:

CypressError: cy.get() could not find a registered alias for: '@mockGraphqlOps'.
Available aliases are: 'mockGraphqlOps:/api'.

Changing the cy.mockGraphql() call to the following resolves the issue:

beforeEach(() => {
    cy.server();
    cy.mockGraphql({
      schema: Cypress.env("GRAPHQL_SCHEMA"),
      endpoint: "/api"
    }).as("mockGraphqlOps");
  });

If this is normal expected behavior, a note in the readme should be added to add .as(). As a newer user of Cypress this tripped me up.

Using graphql-tools' MockList sometimes results in errors.

I ran into a spooky issue when using graphql-tools' MockList to mock lists in my schema, where as soon as I returned a MockList in my mocks or operations object, I'd get an error like this:

GraphQL error: Expected Iterable, but did not find one for field Query.things.

Here's an example Cypress test snippet that reproduces this error:

import schema from '../schema.json';
import { MockList } from 'graphql-tools';

describe('Example', () => {
  beforeEach(() => cy.mockGraphql({ schema }));

  it('Results in an error', () => {
    cy.mockGraphqlOps({
      operations: {
        ExampleQuery: {
          things: [], // returning an empty array works fine...
        },
        AnotherExampleQuery: {
          things: new MockList(9), // but this doesn't!
        },
      },
    });

The error above gets thrown here, because the result instanceof MockList condition always returns false when trying to build the mocked GraphQL response (even though logging result to the console clearly shows it as a MockList).

I believe this is an issue with objects that "travel" between the main Cypress test runner & the actual page via the window:before:load event or the invoke command, since using instanceof to compare objects created in a different window will always return false. (See also: similar issues described in cypress-io/cypress#3420 and cypress-io/cypress#2794.)

Handle multiple queries per request

Thanks for the plugin! I tried it out with my app and it fails on pages where there are multiple graphql queries batched in a single request (one of the strengths of graphql). It manifested as this TypeError: Must provide Source because payload.query was undefined (payload was an array).

https://www.apollographql.com/docs/link/links/batch-http.html

I believe you need to handle when the payload is an array here: https://github.com/tgriesser/cypress-graphql-mock/blob/master/src/index.ts#L101

And just return a single Response.

Promise {<rejected>: Error: Expected "type ...

I have been successfully running cypress-graphql-mock for a while and since updating to cypress 3.8.3 I am getting the error for all my stubs Promise {<rejected>: Error: Expected "type
has anyone encountered this error before. I have tried updating the schema but have not had much luck debugging the issue

any help would be much appreciated

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.