Skip to content

This example shows one approach to unit testing Apollo data sources

Notifications You must be signed in to change notification settings

bysoft/apollo-datasource-rest-testing

 
 

Repository files navigation

Apollo datasource mocks example

This example shows one approach to unit testing Apollo data sources. It uses jest but could easily be replaced by something like mocha and sinon since it does not rely on jest's module mocking functionality.

npm install
npm test

Background

I've struggled with trying to mock out datasources for unit tests (Apollo provides some wonderful GraphQL mocks, but I want to go down a layer to be able to test logic within my datasources). After attempting to things like fetch-mock alongside jest's module mocking features, but had little luck with those approaches due to the nature of how apollo-datasource-rest depends on apollo-server-env which then includes in node-fetch.

I'd be very open to an approach that uses something like fetch-mock to mock at innermost layer (and avoid the need for wrapper code) if it also does not require knowledge of apollo-* internals.

Structure

  • HttpSource is a base class that can be extended by all of the datasources in your application. It provides a 'setMock' method that allows you to provide a mock handler for HTTPSource.fetch calls within your tests
  • CustomDataSource provides an example of a data source that extends HttpSource
  • dataSourceUtil.mockSource provides helpers to make it easier to mock a data source (mockSource(new MyDataSource(), () => ({ mocked: "response" })))

You can see all the components in action in CustomDataSource.test.ts.

About

This example shows one approach to unit testing Apollo data sources

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • TypeScript 93.1%
  • JavaScript 6.9%