Created
October 4, 2023 17:16
-
-
Save jasongaare/5891bff560ceee5b0b8b5cb70f629a1d to your computer and use it in GitHub Desktop.
Example code for creating an Apollo Link and corresponding test
This file contains 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 { ApolloLink, Observable, execute } from '@apollo/client'; | |
// stateful link | |
class OperationHistoryLink extends ApolloLink { | |
operationHistory = []; | |
request(operation, forward) { | |
this.operationHistory.push(operation); | |
return forward(operation); | |
} | |
} | |
// stateless, terminating link | |
const mockLink = new ApolloLink((operation) => { | |
const context = operation.getContext(); | |
const { mockError, mockResponse } = context || {}; | |
return new Observable((observer) => { | |
if (mockError) { | |
observer.error(mockError); | |
return; | |
} | |
if (mockResponse) { | |
observer.next({ data: mockResponse }); | |
observer.complete(); | |
return; | |
} | |
observer.error( | |
new Error('[MockLink]: You must provide mockError or mockResponse'), | |
); | |
}); | |
}); | |
describe('OperationHistoryLink', () => { | |
it('adds operation to the operationHistory array on success', () => { | |
const operationHistoryLink = new OperationHistoryLink(); | |
// create a link chain with our link-to-test and the mockLink | |
const composedLink = operationHistoryLink.concat(mockLink); | |
return new Promise((resolve) => { | |
const operation = { | |
query: 'some query', | |
context: { | |
// test a successful response | |
mockResponse: { foo: 'bar' }, | |
}, | |
}; | |
execute(composedLink, operation).subscribe({ | |
next: ({ data }) => { | |
expect(data.foo).toBe('bar'); // mockResponse is handled by mockLink | |
expect(operationHistoryLink.operationHistory).toHaveLength(1); | |
expect(operationHistoryLink.operationHistory[0].query).toEqual( | |
operation.query, | |
); | |
resolve(); | |
}, | |
error: () => { | |
// optionally reject or throw here, we shouldn't get an error | |
}, | |
complete: () => {}, | |
}); | |
}); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment