Skip to content

Instantly share code, notes, and snippets.

@tdavis
Last active July 25, 2019 17:30
Show Gist options
  • Select an option

  • Save tdavis/3b2068ffbc7ec75d8f4913015bef38ba to your computer and use it in GitHub Desktop.

Select an option

Save tdavis/3b2068ffbc7ec75d8f4913015bef38ba to your computer and use it in GitHub Desktop.
/*
* When using Graphql in NestJS, custom decorator invocations that include pipe
* constructors do not apply ultimately apply said pipes. Passing a pipe _instance_
* works fine, hoever. The following test will fail because we expect that the output
* would be "replacement" per `TestPipe.transform()` while instead it is "original",
* as if from a literal `@CustomParam()`.
*/
import {
createParamDecorator,
INestApplication,
Injectable,
Module,
PipeTransform
} from '@nestjs/common';
import { GraphQLModule, Query, Resolver } from '@nestjs/graphql';
import { Test } from '@nestjs/testing';
import * as request from 'supertest';
import { Field, ObjectType } from 'type-graphql';
@Injectable()
class TestPipe implements PipeTransform {
transform(_token: string): string {
return 'replacement';
}
}
@ObjectType()
class Result {
@Field()
public readonly text: string;
constructor(text: string) {
this.text = text;
}
}
const CustomParam = createParamDecorator(() => 'original');
@Resolver(of => Result)
class TestResolver {
@Query(returns => Result)
result(@CustomParam(TestPipe) value: string): Result {
return new Result({ text: value })
}
}
@Module({
providers: [{ provide: 'resolver', useClass: TestResolver }]
})
class TestModule {}
describe('ContextPipe', () => {
let testHttpServer: request.SuperTest<request.Test>;
let app: INestApplication;
beforeAll(async () => {
const mod = await Test.createTestingModule({
imports: [
TestModule,
GraphQLModule.forRoot({
debug: false,
playground: false,
autoSchemaFile: true,
include: [TestModule],
context: ({ req }) => ({ req }),
}),
],
}).compile();
await mod.init();
app = mod.createNestApplication();
await app.init();
testHttpServer = await request(app.getHttpServer());
});
afterAll(async () => {
await app.close();
});
test('works with resolver', async (done) => {
testHttpServer
.post('/graphql')
.send({
operationName: null,
variables: {},
query: `{ result { text } }`
})
.expect(200, { data: { result: { text: 'replacement' } } })
.end(done);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment