Last active
January 20, 2018 02:27
-
-
Save shlomitc/fcd475d41cf03a5e6db6b5f8ee049f38 to your computer and use it in GitHub Desktop.
A working example of graphql and apollo client test
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'mocha'; | |
import {expect} from 'chai'; | |
import 'isomorphic-fetch'; | |
import ApolloClient from 'apollo-client'; | |
import gql from 'graphql-tag'; | |
import {print} from 'graphql-tag/bundledPrinter'; | |
describe('some test', () => { | |
it('should pass', () => { | |
const query = gql` | |
query people { | |
allPeople(first: 1) { | |
people { | |
name | |
} | |
} | |
} | |
`; | |
const result = { | |
data: { | |
allPeople: { | |
people: [ | |
{ | |
name: 'Luke Skywalker', | |
}, | |
], | |
}, | |
}, | |
}; | |
const networkInterface = new MockNetworkInterface({ | |
request: {query}, | |
result | |
}); | |
const client = new ApolloClient({ | |
networkInterface, | |
addTypename: false | |
}); | |
return client.query({query}) | |
.then(d => { | |
return expect(d.data).to.eql(result.data); | |
}); | |
}); | |
}); | |
class MockNetworkInterface { | |
mockedResponsesByKey = []; | |
constructor(mockedResponse) { | |
this.addMockedResponse(mockedResponse); | |
} | |
addMockedResponse(mockedResponse) { | |
const key = requestToKey(mockedResponse.request); | |
let mockedResponses = this.mockedResponsesByKey[key]; | |
if (!mockedResponses) { | |
mockedResponses = []; | |
this.mockedResponsesByKey[key] = mockedResponses; | |
} | |
mockedResponses.push(mockedResponse); | |
} | |
query(request) { | |
return new Promise((resolve, reject) => { | |
const parsedRequest = { | |
query: request.query, | |
variables: request.variables, | |
debugName: request.debugName, | |
}; | |
const key = requestToKey(parsedRequest); | |
const responses = this.mockedResponsesByKey[key]; | |
if (!responses || responses.length === 0) { | |
throw new Error(`No more mocked responses for the query: ${print(request.query)}, variables: ${JSON.stringify(request.variables)}`); | |
} | |
const {result, error, delay} = responses.shift(); | |
if (!result && !error) { | |
throw new Error(`Mocked response should contain either result or error: ${key}`); | |
} | |
setTimeout(() => { | |
if (error) { | |
reject(error); | |
} else { | |
resolve(result); | |
} | |
}, delay ? delay : 0); | |
}); | |
} | |
} | |
function requestToKey(request) { | |
const queryString = request.query && print(request.query); | |
return JSON.stringify({ | |
variables: request.variables || {}, | |
debugName: request.debugName, | |
query: queryString, | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment