Giter Site home page Giter Site logo

graphql-mock's People

Contributors

gaving avatar kaievns avatar revskill10 avatar s-taylor avatar sekhavati avatar stolinski avatar wesbos 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

Watchers

 avatar  avatar  avatar

graphql-mock's Issues

Pass in custom client?

Apologies for all the issues I'm opening, but I think this package is severely needed right now :)

What do you think about passing in our own apollo client config? I'm asking because I'm using apollo boost which has the local state link, and the one you are using doesn't include that.

Explode when un-mocked query/mutation occurs

Similar to how Nock functions, it would be great if graphql-mock would throw an exception when an un-mocked query or mutation is passed. This would give visibility of when something is not mocked correctly.

Similarly, it would also be nice to add an .isDone() method to use to assert that all mocks that have been setup have been executed.

mutation mocking with .fail throws an error with apollo hooks

When using useMutation and mocking this via graphQL mock to fail (.fail('...')), the result is an error is thrown. But when a graphQL error normally occurs with useMutation no error is thrown, the error is just returned via the error variable.

In the tests this isn't occuring because there is a { onError: noop } passed to the useMutation hook. But this shouldn't be necessary and is masking the problem.

https://github.com/MadRabbit/graphql-mock/blob/master/test/mutations_test.tsx#L41

Test with graphql client directly? (Without React component wrappers)

Hi, first off thanks for providing this library, it is super useful!

I am trying to mock the apollo-graphql client when calling mutate/queries on the client object directly.

This seems to mostly be working, but it seems like the then/catch is never being resolved. Any thoughts? I am not 100% sure that I am initializing everything that is necessary for properly setting up the mocking, but especially when using mutate to create new data, I assume this should work.

I am creating the mock client as follows:

import { addMockFunctionsToSchema } from 'graphql-tools';
import GraphQLMock from 'graphql-mock';
import { buildClientSchema, GraphQLScalarType, Kind } from 'graphql';
const introspectionResult = require('../schema');

addMockFunctionsToSchema({
  schema,
  preserveResolvers: true
});

const graphqlMock = new GraphQLMock(
  schema,
  {
    DateTime: () => {
      return new Date();
    }
  },
  {
    DateTime: new GraphQLScalarType({
      name: 'DateTime',
      description: 'DateTime custom scalar type',
      parseValue(value) {
        return new Date(value); // value from the client
      },
      serialize(value) {
        return value.getTime(); // value sent to the client
      },
      parseLiteral(ast) {
        if (ast.kind === Kind.INT) {
          return parseInt(ast.value, 10); // ast value is always in string format
        }
        return null;
      }
    })
  }
);
const epicMiddleware = createEpicMiddleware(contactEpics, { dependencies: { client: graphqlMock.client } });
const mockStore = configureMockStore([epicMiddleware]);

Usage:

const createAsyncEpic = <P1, P2, P3>(
  actions: { request: any; success: any; failure: any },
  mutation: any,
  isProtected: boolean = false
) => {
  const epic: Epic<RootAction, RootState> = (action$, state$, { client }) =>
    action$.pipe(
      filter(isActionOf(actions.request)),
      withLatestFrom(state$),
      mergeMap(([action, state]) => {
        return client
          .mutate({ mutation, variables: { ...(action as any).payload } })
          .then((result: ApolloQueryResult<P2>) => {
            console.log('hello world');
            console.log(`success: ${JSON.stringify(result.data)}`);
            return actions.success(result.data);
          })
          .catch((error: ApolloError) => {
            console.log(`failure: ${JSON.stringify(error)}`);
            return actions.failure(error.graphQLErrors[0].message);
          });
      })
    );
 
  return epic;
};

I guess I am really just using this mock client as the "server" per say, maybe this is the wrong way to go about what I am trying to test.

Fires onCompleted incorrectly for loading mutation

I noticed when writing tests that if you set .loading(true) on a mutation mock, it will still fire the onCompleted function passed to the mutation options. This shouldn't happen until loading is done i.e. not at all when .loading(true)

Add parameter matching

Currently the mocks you setup do not consider the parameters provided, and return the mocked result regardless. It would be great to be able to define the parameters expected and if they do not match do not return the mocked result.

This would enable mocking the same query and having it return different results when different parameters are received which currently is not possible.

Typescript error

Hi there I'm getting an error compiling typescript that I can't quite figure out.

I assumed that the issue was from /graphql-mock/dist/client.d.ts
mutate<T>(options: MutationOptions<T>): Promise<FetchResult<T, any>>
not being the same as /apollo-client/ApolloClient.d.ts
mutate<T>(options: MutationOptions<T>): Promise<FetchResult<T>>

However updating that doesn't work for me. Removing the entire mutate line from graphql-mock/dist/client.d.ts makes it compile but isn't ideal.

Full error message:

(12,5): Property 'mutate' in type 'MockClient' is not assignable to the same property in base type 'ApolloClient<NormalizedCacheObject>'.
  Type '<T>(options: MutationOptions<T>) => Promise<FetchResult<T, any>>' is not assignable to type '<T>(options: MutationOptions<T>) => Promise<FetchResult<T, Record<string, any>>>'.
    Type 'Promise<FetchResult<T, any>>' is not assignable to type 'Promise<FetchResult<T, Record<string, any>>>'.
      Type 'FetchResult<T, any>' is not assignable to type 'FetchResult<T, Record<string, any>>'.
        Type 'FetchResult<T, any>' is not assignable to type 'ExecutionResult'.
          Types of property 'errors' are incompatible.
            Type 'GraphQLError[] | undefined' is not assignable to type 'ReadonlyArray<GraphQLError> | undefined'.
              Type 'GraphQLError[]' is not assignable to type 'ReadonlyArray<GraphQLError> | undefined'.
                Type 'GraphQLError[]' is not assignable to type 'ReadonlyArray<GraphQLError>'.
                  Types of property 'flatMap' are incompatible.
                    Type '<U, This = undefined>(callback: (this: This, value: GraphQLError, index: number, array: GraphQLEr...' is not assignable to type '<U, This = undefined>(callback: (this: This, value: GraphQLError, index: number, array: GraphQLEr...'. Two different types with this name exist, but they are unrelated.
                      Types of parameters 'callback' and 'callback' are incompatible.
                        Types of parameters 'value' and 'value' are incompatible.
                          Type 'GraphQLError' is not assignable to type 'GraphQLError'. Two different types with this name exist, but they are unrelated.
                            Property 'locations' is optional in type 'GraphQLError' but required in type 'GraphQLError'.

Package Versions

"typescript": "^2.8.3"
"graphql-mock": "^1.0.2",
"apollo-boost": "0.1.6",

How to define mocks

Guys, I have just spent 2 hours trying to figure out how to define mocks.
You mention the standard way.

The standard mosck is following:

const mocks = [
  {
    request: {
      query: QUERY,
      variables: {
        from: 1,
        to: 10
      },
    },
    result: {
      data: {
        notifications: [{ id: '1', name: 'Buck', breed: 'bulldog' }],
      },
    },
  },
];

I keep getting all kinds of errors. Would you be so kind and help a pal out with otherwise excellent plugin? You do not have a single example with a mock .. or maybe I'm blind.

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.