Skip to content

Instantly share code, notes, and snippets.

View JakeDawkins's full-sized avatar

Jake Dawkins JakeDawkins

View GitHub Profile
it('should render loading state initially', () => {
const component = renderer.create(
<MockedProvider mocks={[]}>
<Dog />
</MockedProvider>,
);
const tree = component.toJSON();
expect(tree.children).toContain('Loading...');
});
// dog.test.js
import { MockedProvider } from 'react-apollo/test-utils';
// The component AND the query need to be exported
import { GET_DOG_QUERY, Dog } from './dog';
const mocks = [
{
request: {
// Not predictable
it('renders without error', () => {
renderer.create(
<ApolloProvider client={client}>
<Dog name="Buck" />
</ApolloProvider>,
);
});
// Broken because it's missing Apollo Client in the context
it('should render without error', () => {
renderer.create(<Dog name="Buck" />);
});
import React from 'react';
import gql from 'graphql-tag';
import { Query } from 'react-apollo';
// Make sure the query is also exported -- not just the component
export const GET_DOG_QUERY = gql`
query getDog($name: String) {
dog(name: $name) {
id
name
// src/server.js
context: ({ req }) => {
// pass the request information through to the model
return {
user,
models: {
User: generateUserModel({ req }),
...
}
};
getAll: () => {
if(!user || !user.roles.includes('admin')) return null;
return fetch('http://myurl.com/users');
}
export const generateUserModel = ({ user }) => ({
getAll: () => { /* fetching/transform logic for all users */ },
getById: (id) => { /* fetching/transform logic for a single user */ },
getByGroupId: (id) => { /* fetching/transform logic for a group of users */ },
});
context: ({ req }) => {
// get the user token from the headers
const token = req.headers.authentication || '';
// try to retrieve a user with the token
const user = getUser(token);
// optionally block the user
// we could also check user roles/permissions here
if (!user) throw new AuthenticationError('you must be logged in to query this schema');
type Query {
user (id: ID!): User
article (id: ID!): Article
}
type Article {
author: User
}
type User {