Jest testing of Apollo Client GQL query - graphql

Apollo Client lets you directly execute queries for example.
import { ApiClient } from './index'
import gql from 'graphql-tag'
export const query = (data) => ApiClient.query({
query: gql`
query {
users (user:"${data.id}") {
name
}
}
`
})
.then(data => { return data.data.users })
.catch(e => { return e })
I was wondering if anyone had experience writing Jest tests for these.
All I've found is examples using react-apollo etc

If you just want to test your queries and mutations, I recommend testing that on the back end.
take a look at this article here: Testing GraphQL

Related

Apollo-client State management cache is not updating automatically after save and delete operation

I am using apollo-client for graphql calls along with I added state management with in the package apollo-client. In graphql module, assigned InMemoryCache to cache variable and client variable is exported.Client variable is imported in component so data is available in client.cache.data after default get call executed but I want to update client cache after save and delete graphql operations success callbacks
Here is my graphql.module.ts:
import {NgModule} from '#angular/core';
import {ApolloModule, APOLLO_OPTIONS} from 'apollo-angular';
import { ApolloClient } from 'apollo-client';
import {InMemoryCache} from 'apollo-cache-inmemory';
import { HttpLink } from 'apollo-link-http';
const cache = new InMemoryCache();
const link = new HttpLink({
uri:'https://api.graph.cool/simple/v1/ciyz901en4j590185wkmexyex'
});
export var client = new ApolloClient({
cache,
link
});
#NgModule({
})
and my service call implementation
client
.query({
query: gql`
{
fORoomTypes()
{
nodes
{
roomTypeId
roomType
ratSingle
ratDouble
ratExtra
statu
}
}
}
`,
})
.then(result => {
callback(result);
});
after callback client.cache.data contain data, I want to call this data with cache queries and I want to update cache automatically
this is my save service implementation
const post = gql`
mutation
{
saveRtype(rt:
{
rty:
{
rt:"Club room"
rat:4000
cchub:4500
ext:800
statu:1
}
traCheck:1
}
)
}
`
client.mutate({
mutation: post
}).then((data) => {
callback(data)
});
I've only used apollo client with React but hopefully can shed light on how it works. For this to happen "automatically", you either need to call refetchQueries to refetch fORoomTypes after the mutation, or manually update the cache. I noticed your responses do not return an id property, so how would it know which one to update? If there is an identifier that isn't called "id", then register it following this documentation.
Here is the link to documentation in general for what you want
https://www.apollographql.com/docs/angular/features/cache-updates/

Apollo client useQuery not updating data after useMutation

Using this mutation:
import produce from 'immer
const [createItem] = useMutation(CREATE_ITEM, {
update (client, { data: { createItem } }) {
const queryResults = client.readQuery({
query: GET_LATEST_ORDER,
variables: { orderDepth: 1 }
})
client.writeQuery({
query: GET_LATEST_ORDER,
variables: { orderDepth: 1 },
data: produce(queryResults, draft => {
draft.orders[0].items.push(createItem)
})
})
}
})
I am unable to get
const { loading, data, refetch } = useQuery(GET_LATEST_ORDER, {
variables: { orderDepth: 1 }
})
to show updated data after the mutation.
The apollo cache is updated correctly. But data on the useQuery does not change.
The issue ended up being the returned object from the mutation was not exactly the same. It was missing an #client field.
While obvious in hindsight no where I searched described this as a reason except for a comment I saw mentioning perhaps missing the __typename.
This would have been obvious had apollo thrown an error. However, no error was thrown, nor existed on the useQuery.

Apollo Query with Variable

Just a basic apollo query request
this.client.query({
query: gql`
{
User(okta: $okta){
id
}
}`
}).then(result => {
this.setState({userid: result.data.User});
console.log(this.state.userid.id)
}).catch(error => {
this.setState({error: <Alert color="danger">Error</Alert>});
});
The question is, how/where to set the $okta variable.
Didn't find a solution on Stackoverflow or Google - would be great if someone could help me:)
It should be something like this:
const query = gql`
query User($okta: String) {
User(okta: $okta){
id
}
}
`;
client.query({
query: query,
variables: {
okta: 'some string'
}
})
The documentation for Apollo client with all the details can be found here: https://www.apollographql.com/docs/react/api/apollo-client.html#ApolloClient.query

Querying REST API with Cursor Pagination from Server with Apollo-Server-Express

Using Apollo-Server-Express, I want to wrap a REST API with GraphQL. I'm starting with the free to use SWAPI (Star Wars API). I can't find anything about server side fetching with cursor paging using apollo-server-express. The only thing that I found that could be a possibility since it's for the Apollo Client is fetchMore. Any help would be greatly appreciated. Here's my code:
schema.js
// Imports: GraphQL
import { makeExecutableSchema } from 'graphql-tools';
// Imports: GraphQL TypeDefs & Resolvers
import TYPEDEFS from './types.js';
import RESOLVERS from './resolvers.js';
// GraphQL: Schema
const SCHEMA = makeExecutableSchema({
typeDefs: TYPEDEFS,
resolvers: RESOLVERS
});
export default SCHEMA;
types.js
const TYPEDEFS = `
type Query {
getFilm(id: ID): Film
getAllFilms: [Film]
}
type Film {
title: String!
episode_id: Int!
opening_crawl: String
director: String
producer: String
release_date: String
characters: [Person]
planets: [Planet]
starships: [Starship]
vehicles: [Vehicle]
species: [Species]
created: String
edited: String
url: String
}
}`
export default TYPEDEFS;
resolvers.js
import fetch from 'node-fetch';
const RESOLVERS = {
Query: {
// Search for a Film by ID
getFilm: async (parent, args) => {
const response = await
fetch(`https://swapi.co/api/films/${args.id}`);
return response.json();
},
getAllFilms: async (parent, args) => {
const response = await
fetch(`https://swapi.co/api/films/`);
return response.json();
}
}
};
export default RESOLVERS;
I believe apollo-server does not provide cursor pagination out of the box.
You can either implement it yourself. Or you can use(or get inspired) by the one that Relay uses.
And according to Apollo client if you use Relay style cursor pagination the client has support for it.

Update method in mutation not running

I have the following component that mutates data. Apollo provides functionality to update the store automatically. I would like to control the way the data is added to the store using the update function. The documentation is straightforward enough, but I can't get it working. What is wrong in the code below that would prevent the console.log from printing.
import React from 'react'
import { connect } from 'react-redux';
import { graphql, gql, compose } from 'react-apollo';
import { personCodeSelector } from '../../selectors/auth';
import UploadBankStatement from '../../components/eftFileUploads/UploadBankStatement.jsx';
const createEftFileUpload = gql`mutation createEftFileUpload(
$bankAccountCode: String!,
$uploadInput: UploadInput!,
$uploadedByPersonCode: String!) {
createEftFileUpload(
bankAccountCode: $bankAccountCode,
uploadInput: $uploadInput,
uploadedByPersonCode: $uploadedByPersonCode) {
id
bankAccountCode
fileName
numberOfProcessedItems
numberOfUnallocatedItems
createdAt
status
}
}`;
const mutationConfig = {
props: ({ ownProps, mutate }) => ({
createEftFileUpload: (bankAccountCode, uploadInput) => {
return mutate({
variables: {
bankAccountCode,
uploadInput,
uploadedByPersonCode: ownProps.personCode
},
update: (store, something) => {
console.log("ping");
console.log(store, something);
},
});
}
})
};
const mapStateToProps = state => {
return {
personCode: personCodeSelector(state)
};
};
export default compose(
connect(mapStateToProps),
graphql(createEftFileUpload, mutationConfig)
)(UploadBankStatement);
Note I have found a couple of similar issues, but it doesn't seem to shed any light on my situation.
Server restart fix my issue. Not sure why this was required with hot-reloading. The code was correct.

Resources