Skip to content

Commit 291d5c5

Browse files
committed
test: custom context is available to resolvers
1 parent 5a1e97c commit 291d5c5

File tree

3 files changed

+81
-0
lines changed

3 files changed

+81
-0
lines changed
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
import { INestApplication } from '@nestjs/common';
2+
import { ExpressAdapter } from '@nestjs/platform-express';
3+
import { Test } from '@nestjs/testing';
4+
import * as request from 'supertest';
5+
import { CustomContextModule } from '../graphql/custom-context/custom-context.module';
6+
import { FastifyAdapter } from '@nestjs/platform-fastify';
7+
8+
describe('GraphQL (custom context)', () => {
9+
let app: INestApplication;
10+
11+
describe.each([
12+
['Express', new ExpressAdapter()],
13+
['Fastify', new FastifyAdapter()],
14+
])('Custom context with %s', (_, adapter) => {
15+
beforeEach(async () => {
16+
const module = await Test.createTestingModule({
17+
imports: [CustomContextModule],
18+
}).compile();
19+
20+
app = module.createNestApplication(adapter);
21+
await app.init();
22+
23+
const instance = app.getHttpAdapter().getInstance();
24+
if ('ready' in instance && typeof instance.ready === 'function') {
25+
await instance.ready();
26+
}
27+
});
28+
29+
it('should return query result', () => {
30+
return request(app.getHttpServer())
31+
.post('/graphql')
32+
.send({
33+
operationName: null,
34+
variables: {},
35+
query: `
36+
{
37+
fooFromContext
38+
}
39+
`,
40+
})
41+
.expect(200, {
42+
data: {
43+
fooFromContext: 'bar',
44+
},
45+
});
46+
});
47+
48+
afterEach(async () => {
49+
await app.close();
50+
});
51+
});
52+
});
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import { Module } from '@nestjs/common';
2+
import { GraphQLModule } from '@nestjs/graphql';
3+
import { ApolloDriverConfig } from '../../../lib';
4+
import { ApolloDriver } from '../../../lib/drivers';
5+
import { CustomContextResolver } from './custom-context.resolver';
6+
7+
@Module({
8+
imports: [
9+
GraphQLModule.forRoot<ApolloDriverConfig>({
10+
driver: ApolloDriver,
11+
autoSchemaFile: true,
12+
context: (request) => ({
13+
foo: 'bar',
14+
request,
15+
}),
16+
}),
17+
],
18+
providers: [CustomContextResolver],
19+
})
20+
export class CustomContextModule {}
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
import { Resolver, Query, Context } from '@nestjs/graphql';
2+
3+
@Resolver()
4+
export class CustomContextResolver {
5+
@Query(() => String)
6+
fooFromContext(@Context() ctx: Record<string, unknown>) {
7+
return ctx.foo;
8+
}
9+
}

0 commit comments

Comments
 (0)