【发布时间】:2017-01-23 16:34:31
【问题描述】:
上下文
我有一个基本的PipeTransform,期望它是异步的。为什么?因为我有自己的 i18n 服务(因为解析、复数和其他限制,我自己做了),它返回一个 Promise<string>:
@Pipe({
name: "i18n",
pure: false
})
export class I18nPipe implements PipeTransform {
private done = false;
constructor(private i18n:I18n) {
}
value:string;
transform(value:string, args:I18nPipeArgs):string {
if(this.done){
return this.value;
}
if (args.plural) {
this.i18n.getPlural(args.key, args.plural, value, args.variables, args.domain).then((res) => {
this.value = res;
this.done = true;
});
}
this.i18n.get(args.key, value, args.variables, args.domain).then((res) => {
this.done = true;
this.value = res;
});
return this.value;
}
}
这个管道很好用,因为唯一的延迟调用是第一个调用(I18nService 使用延迟加载,只有在找不到密钥时才加载 JSON 数据,所以基本上第一次调用会被延迟,其他的是即时的,但仍然是异步的)。
问题
我不知道如何使用Jasmine 测试这个管道,因为它在一个我知道它可以工作的组件中工作,但这里的目标是使用 jasmine 对它进行全面测试,这样我可以添加它到 CI 例程。
以上测试:
describe("Pipe test", () => {
it("can call I18n.get.", async(inject([I18n], (i18n:I18n) => {
let pipe = new I18nPipe(i18n);
expect(pipe.transform("nope", {key: 'test', domain: 'test domain'})).toBe("test value");
})));
});
因为I18nService 给出的结果是异步的,所以失败,返回的值在同步逻辑中是未定义的。
I18n 管道测试可以调用 I18n.get。失败
预期未定义为“测试值”。
编辑:一种方法是使用setTimeout,但我想要一个更漂亮的解决方案,以避免在任何地方添加setTimeout(myAssertion, 100)。
【问题讨论】:
标签: asynchronous angular jasmine angular2-testing angular2-pipe