Created
January 22, 2020 18:05
-
-
Save slmyers/a12f8c9b2100578860c149171df6dc09 to your computer and use it in GitHub Desktop.
how to mock graphql context in a 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
// in src/schema.spec.js | |
const { graphql } = require('graphql'); | |
const schema = require('./schema'); | |
it('responds to the Tweets query', () => { | |
// stubs | |
const queryStub = q => { | |
if (q == 'SELECT * from tweets') { | |
return Promise.resolve({ rows: [ | |
{ id: 1, body: 'Lorem Ipsum', date: new Date(), author_id: 10 }, | |
{ id: 2, body: 'Sic dolor amet', date: new Date(), author_id: 11 } | |
]}); | |
} | |
}; | |
const dataloaders = { | |
userById: { | |
load: id => { | |
if (id == 10 ) { | |
return Promise.resolve({ id: 10, username: 'johndoe', first_name: 'John', last_name: 'Doe', avatar_url: 'acme.com/avatars/10' }); | |
} | |
if (id == 11 ) { | |
return Promise.resolve({ | |
{ id: 11, username: 'janedoe', first_name: 'Jane', last_name: 'Doe', avatar_url: 'acme.com/avatars/11' }); | |
} | |
} | |
} | |
}; | |
const context = { pgClient: { query: queryStub }, dataloaders }; | |
// now onto the test itself | |
const query = '{ Tweets { id body Author { username } }}'; | |
return graphql(schema, query, null, context).then(results => { | |
expect(results).toEqual({ | |
data: { | |
Tweets: [ | |
{ id: '1', body: 'hello', Author: { username: 'johndoe' } }, | |
{ id: '2', body: 'world', Author: { username: 'janedoe' } }, | |
], | |
}, | |
}); | |
}); | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment