【发布时间】:2018-08-22 10:01:23
【问题描述】:
我有一个服务被注入到 AppModule 中并且是一个单例,它使用一个 swagger 生成的 API 服务:
export class QueryService {
public cache: Map<string, EvaluationResult> = new Map<string, EvaluationResult>();
constructor(
private queryService: QueryApi,
) { }
public hashQueries(queries: Query[]): string {
const hashedQueries: string[] = [];
for (const query of queries) {
hashedQueries.push(query.hashCode());
}
hashedQueries.sort();
const hashcode = new Md5();
hashcode.appendStr(hashedQueries.join(","));
return (hashcode.end() as string);
}
}
如您所见,此服务使用缓存。每个查询都使用哈希码保存到缓存中,当调用该方法时,我检查该查询是否已存在于缓存中。
我想编写一个测试来检查 hashcode 函数是否有效。目前我有这样的事情:
describe("QueryService", () => {
it("should return a valid hashcode", () => {
// make one type of query
// make another type of query
let service: QueryService;
const queries = [attributeQuery, sodQuery];
const hashcode = service.hashQueries(queries);
expect(hashcode).toBeDefined();
expect(hashcode.length).toBe(32);
});
it("should return the same hashcode", () => {
// make two types of queries again but place them
// in a different order
});
it("should return a different hashcode", () => {
// make two types of queries again but change a
// tiny detail so the hashcode is different
});
}
如您所见,我想使用 QueryService,它是 hashQueries() 函数,而实际上不需要组件。初始化这样的服务并不理想,因为它的构造函数需要另一个 API 服务,这也需要其他参数。
有没有简单的方法来使用这项服务?
提前致谢!
【问题讨论】:
-
您应该考虑模拟服务
QueryApi。而且我也没有看到QueryApi实例的任何用法。 -
@AmitChigadani QueryApi 将请求发送到服务器。我在这里不需要那个功能,因为我只想测试哈希函数。但是需要启动一个QueryService对象
-
如果你不需要,那么只需将 null 传递给你的构造函数
-
@AmitChigadani 叹息...我真的没有想到,多么尴尬!谢谢!
-
也很好奇,你的
TesBed服务配置在哪里?
标签: angular jasmine karma-jasmine angular6