Skip to content

Instantly share code, notes, and snippets.

@kristianmandrup
Last active October 23, 2019 19:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save kristianmandrup/1f7e4a550e6c32b99881aa1b78a4a440 to your computer and use it in GitHub Desktop.
Save kristianmandrup/1f7e4a550e6c32b99881aa1b78a4a440 to your computer and use it in GitHub Desktop.
LevelUp Tuts: mockMang for testing Apollo GraphQL
import { makeExecutableSchema, addMockFunctionsToSchema } from "graphql-tools";
import { graphql } from "graphql";
import { ApolloClient } from "apollo-client";
import { from } from "apollo-link";
import { withClientState } from "apollo-link-state";
import { InMemoryCache } from "apollo-cache-memory";
import GoalsSchema from "../api/goals/Goal.graphql";
// import { defaultState } from '../ui/config/apollo/defaultState'
const defaultState = {};
// import { defaultState } from '../ui/config/apollo/stateMutations'
const stateMutations = {};
const stateLink = withClientState({
cache: new InMemoryCache(),
resolvers: stateMutations,
defaults: defaultState
});
// client.onResetStore(stateLink.writeDefaults)
const link = from({ stateLink });
const client = new ApolloClient({
link,
cache: new InMemoryCache()
});
const typeDefs = [GoalsSchema];
const schema = makeExecutableSchema({ typeDefs });
const revisedRandId = () =>
Math.random()
.toString(36)
.replace(/[^a-z]+/g, "")
.substr(2, 10);
// mock order
const order = {};
// mock user
const user = {};
const product = {};
const allProducts = [product];
const mocks = {
ID: () => revisedRandId(),
Product: () => ({
...product
}),
Order: () => ({
...order
}),
User: () => ({
...user
})
};
addMockFunctionsToSchema({ schema, mocks });
const mockMang = async (query, args = {}) => {
try {
const res = await graphql(schema, query.loc.source.body, null, null, args);
res.data.loading = false;
return res.data;
} catch (err) {
return console.log(err.message);
}
};
export { client };
export const mockFunc = () => null;
export const mockAsyncFunc = async () => true;
export default mockMang;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment