【发布时间】:2019-09-24 03:27:30
【问题描述】:
测试 Apollo GraphQL 服务器的标准方法是使用Apollo test client。
createTestClient 方法需要 server 参数。
在 NestJS/TypeGraphQL 应用程序中,从 (Jest) 测试内部访问由 GraphQLModule 创建的 Apollo 服务器的适当方法是什么?
【问题讨论】:
测试 Apollo GraphQL 服务器的标准方法是使用Apollo test client。
createTestClient 方法需要 server 参数。
在 NestJS/TypeGraphQL 应用程序中,从 (Jest) 测试内部访问由 GraphQLModule 创建的 Apollo 服务器的适当方法是什么?
【问题讨论】:
const moduleFixture = await Test.createTestingModule({
imports: [ApplicationModule],
}).compile()
const app = await moduleFixture.createNestApplication(new ExpressAdapter(express)).init()
const module: GraphQLModule = moduleFixture.get<GraphQLModule>(GraphQLModule)
const apolloClient = createTestClient((module as any).apolloServer)
这就是我的工作
【讨论】:
TypeError: Cannot read property 'executeOperation' of undefined,因为 module.apolloServer 未定义。 NestFactory.createApplicationContext(AppModule) 也是如此。使用"@nestjs/graphql": "^6.5.1"
此 PR https://github.com/nestjs/graphql/pull/1104 使您能够使用 apollo-server-testing 编写测试。
【讨论】:
这段代码对我有用。感谢 JustMe
import { Test, TestingModule } from '@nestjs/testing';
import { INestApplication } from '@nestjs/common';
import { createTestClient, TestQuery } from 'apollo-server-integration-testing';
import { AppModule } from './../src/app.module';
import { GraphQLModule } from '@nestjs/graphql';
describe('AppController (e2e)', () => {
let app: INestApplication;
// let mutateTest: TestQuery;
let correctQueryTest: TestQuery;
let wrongQueryTest: TestQuery;
beforeEach(async () => {
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [AppModule],
}).compile();
app = moduleFixture.createNestApplication();
await app.init();
const module: GraphQLModule =
moduleFixture.get<GraphQLModule>(GraphQLModule);
const { query: correctQuery } = createTestClient({
apolloServer: (module as any).apolloServer,
extendMockRequest: {
headers: {
token:
'iIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI2MWFiNmY0MjQ3YjEyYWNiNzQyYmQwYmYiLCJyb2xlIjoibWFuYWdlciIsImVtYWlsIjoibGVuYUBtYWlsLmNvbSIsInBhc3N3b3JkIjoiZTEwYWRjMzk0OWJhNTlhYmJlNTZlMDU3ZjIwZjg4M2UiLCJ1c2VybmFtZSI6ImxlbmEgZG9lIiwiY3JlYXRlZEF0IjoiMjAyMS0xMi0wNFQxMzozODoxMC4xMzZaIiwidXBkYXRlZEF0IjoiMjAyMS0xMi0wNFQxMzozODoxMC4xMzZaIiwiX192IjowLCJpYXQiOjE2Mzg2NTE4MjMsImV4cCI6MTYzODY1MTg4M30.d6SCh4x6Wwpj16UWf4ca-PbFCo1FQm_bLelp8kscG8U',
},
},
});
const { query: wrongQuery } = createTestClient({
apolloServer: (module as any).apolloServer,
});
// mutateTest = mutate;
correctQueryTest = correctQuery;
wrongQueryTest = wrongQuery;
});
it('/ Correct', async () => {
const result = await correctQueryTest(`
query FILTER_JOBS{
filterJobs(status: DONE) {
title,
status,
description,
lat,
long,
employees,
images,
assignedBy {
username,
email
}
}
}
`);
console.log(result);
});
it('/ Wrong', async () => {
const result = await wrongQueryTest(`
query FILTER_JOBS{
filterJobs(status: DONE) {
title,
status,
description,
lat,
long,
employees,
images,
assignedBy {
username,
email
}
}
}
`);
console.log(result);
});
});
【讨论】: