【发布时间】:2017-12-08 01:46:52
【问题描述】:
我正在尝试测试我的模块构造函数之一中的代码。基本上,模块(名为GraphqlModule)配置一个服务(名为Graphql)并提供它。配置发生在模块的构造函数中。
这是我用来测试模块的代码。
it('should use the GraphqlConfigs and ServerConfigs', (done: DoneFn) => {
// Adding spies to Config classes
let serverConfigs = new ServerConfigs();
let serverDomainSpy = spyOnProperty(serverConfigs, 'ServerDomain', 'get').and.callThrough();
let serverPortSpy = spyOnProperty(serverConfigs, 'ServerPort', 'get').and.callThrough();
let gqlConfigs = new GraphqlConfigs();
let protocolSpy = spyOnProperty(gqlConfigs, 'EndpointProtocol', 'get').and.callThrough();
let endpointNameSpy = spyOnProperty(gqlConfigs, 'EndpointName', 'get').and.callThrough();
TestBed.configureTestingModule({
imports: [ GraphqlModule ],
providers: [
{provide: ServerConfigs, useValue: serverConfigs}, // Replacing real config classes with the ones spied on.
{provide: GraphqlConfigs, useValue: gqlConfigs}
]
}).compileComponents().then(() => {
// This line seems to make Angular instantiate GraphqlModule
const graphql = TestBed.get(Graphql) as Graphql;
expect(serverDomainSpy.calls.count()).toBe(1, 'ServerConfigs.ServerDomain was not used.');
expect(serverPortSpy.calls.count()).toBe(1, 'ServerConfigs.ServerPort was not used.');
expect(protocolSpy.calls.count()).toBe(1, 'GraphqlConfigs.EndpointProtocol was not used.');
expect(endpointNameSpy.calls.count()).toBe(1, 'GraphqlConfigs.EndpointName was not used.');
done();
});
});
按原样,测试通过并正常工作,但如果我不使用以下(无用的)行const graphql = TestBed.get(Graphql) as Graphql;,GraphqlModule 在测试执行后会被实例化,这会使测试失败。
由于提供Graphql 服务的是GraphqlModule,我知道当我执行TestBed.get(Graphql) 时会触发Angular 中的一些延迟加载算法。没关系...我的问题是,有没有办法让我的模块以更explicit的方式加载?
这是 GraphqlModule 类的定义:
imports...
@NgModule({
imports: [
CommonModule,
HttpClientModule,
ApolloModule,
HttpLinkModule
],
declarations: [],
providers: [
Graphql, // Is an alias for Apollo
GraphqlConfigs
]
})
export class GraphqlModule {
constructor(
@Optional() @SkipSelf() parentModule: GraphqlModule,
graphql: Graphql,
httpLink: HttpLink,
serverConfigs: ServerConfigs,
graphqlConfigs: GraphqlConfigs
) {
// Making sure this is not imported twice.
// https://angular.io/guide/ngmodule#prevent-reimport-of-the-coremodule
if (parentModule) {
throw new Error(
'GraphqlModule is already loaded. Import it in the '+CoreModule.name+' only.');
}
// Gql setup:
const gqlHttpLink = httpLink.create({
uri: GraphqlModule.buildEndpointUrl(serverConfigs, graphqlConfigs)
});
graphql.create({
link: gqlHttpLink,
cache: new InMemoryCache(),
});
}
private static buildEndpointUrl(serverConfigs: ServerConfigs, graphqlConfigs: GraphqlConfigs): string {
return graphqlConfigs.EndpointProtocol + // eg. http://
serverConfigs.ServerDomain+":"+serverConfigs.ServerPort+'/' + // eg. example.com:80/
graphqlConfigs.EndpointName; // eg. graphql
}
}
【问题讨论】:
-
不清楚您在测试什么,因为问题不包含 GraphqlModule 或 Graphql。 我正在尝试测试我的模块构造函数之一中的代码 - 它没有列出。
-
@estus 该模块列在
Testbed的导入配置中。此测试是测试套件的一部分,用于测试GraphqlModule的不同功能 -
对不起,我把它放在问题的正文中,但是我不确定它是否与我的问题有关。
-
有必要了解发生了什么,谢谢。