|
| 1 | +import { ApolloServer, type ApolloServerOptions, type BaseContext } from '@apollo/server'; |
| 2 | +import { |
| 3 | + defineIntegrationTestSuite, |
| 4 | + type CreateServerForIntegrationTestsOptions, |
| 5 | +} from '@apollo/server-integration-testsuite'; |
| 6 | +import type { Server } from 'http'; |
| 7 | +import type { AddressInfo } from 'net'; |
| 8 | +import { format } from 'url'; |
| 9 | +import { startServerAndCreateGoogleCloudFunctionsHandler } from '..'; |
| 10 | + |
| 11 | +const { getTestServer } = require('@google-cloud/functions-framework/testing'); |
| 12 | + |
| 13 | +describe('cloud functions handler', () => { |
| 14 | + defineIntegrationTestSuite( |
| 15 | + async function ( |
| 16 | + serverOptions: ApolloServerOptions<BaseContext>, |
| 17 | + testOptions?: CreateServerForIntegrationTestsOptions, |
| 18 | + ) { |
| 19 | + const apolloServer = new ApolloServer({ |
| 20 | + ...serverOptions, |
| 21 | + }); |
| 22 | + |
| 23 | + startServerAndCreateGoogleCloudFunctionsHandler(apolloServer, { |
| 24 | + functionTarget: 'apolloServer', |
| 25 | + context: testOptions?.context, |
| 26 | + }); |
| 27 | + |
| 28 | + const testServer = getTestServer('apolloServer'); |
| 29 | + await new Promise<void>((resolve) => { |
| 30 | + testServer.listen({ port: 0 }, resolve); |
| 31 | + }); |
| 32 | + |
| 33 | + return { |
| 34 | + server: apolloServer, |
| 35 | + url: urlForHttpServer(testServer), |
| 36 | + async extraCleanup() { |
| 37 | + await new Promise<void>((resolve) => { |
| 38 | + testServer.close(() => resolve()); |
| 39 | + }); |
| 40 | + }, |
| 41 | + }; |
| 42 | + }, |
| 43 | + { |
| 44 | + serverIsStartedInBackground: true, |
| 45 | + noIncrementalDelivery: true, |
| 46 | + }, |
| 47 | + ); |
| 48 | +}); |
| 49 | + |
| 50 | +// Stolen from apollo server integration tests |
| 51 | +export function urlForHttpServer(httpServer: Server): string { |
| 52 | + const { address, port } = httpServer.address() as AddressInfo; |
| 53 | + |
| 54 | + // Convert IPs which mean "any address" (IPv4 or IPv6) into localhost |
| 55 | + // corresponding loopback ip. Note that the url field we're setting is |
| 56 | + // primarily for consumption by our test suite. If this heuristic is wrong for |
| 57 | + // your use case, explicitly specify a frontend host (in the `host` option |
| 58 | + // when listening). |
| 59 | + const hostname = address === '' || address === '::' ? 'localhost' : address; |
| 60 | + |
| 61 | + return format({ |
| 62 | + protocol: 'http', |
| 63 | + hostname, |
| 64 | + port, |
| 65 | + pathname: '/', |
| 66 | + }); |
| 67 | +} |
0 commit comments