kaievns / graphql-mock Goto Github PK
View Code? Open in Web Editor NEWA client side GraphQL mocking library
A client side GraphQL mocking library
Is is possible to also check if mutations were called with this library? Or just queries?
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.
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.
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
Thanks for the great library - I'm looking to test my loading and error states - how would I trigger these states with this library?
Any idea on how to mock Subscription ?
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.
There is no way to pass custom resolver to makeExecutableSchema
.
I needed it because I have this exact problem
More specifically: I get GraphQL error: No mock defined for type "DateTime"
and GraphQL error: Expected a value of type "DateTime" but received: Mon Apr 16 2018 13:30:47 GMT+0200 (CEST)
and I figured I need to replace the resolver to fix it.
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)
I think when you published 0.2.0 this commit didn't make it:
https://unpkg.com/[email protected]/dist/client.ts
Could you re-pull and re-publish? Thank you : )
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.
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",
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.
this makes navigating to the repo on npm difficult
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.