Sup*_*miu 5 jasmine typescript karma-jasmine angular
我正在测试一个组件,该组件使用基于可观察的服务来获取一些数据并显示它用于i18n目的.
由于特定需要,i18n服务是定制的.
该组件在开发模式下工作(在某些模板中使用,工作正常)但测试失败.
@Component({
selector : "i18n",
template : '<span [innerHTML]="text"></span><span #wrapper hidden="true"><ng-content></ng-content><span>',
encapsulation: ViewEncapsulation.None
})
export class I18nComponent implements OnChanges {
constructor(private i18n:I18n) {
}
@ViewChild('wrapper')
content:ElementRef;
@Input('key')
key:string;
@Input('domain')
domain:string;
@Input('variables')
variables:Variables = [];
@Input("plural")
plural:number;
text:string;
ngOnChanges():any {
this.i18n.get(this.key, this.content.nativeElement.innerHTML, this.variables, this.domain).subscribe((res) => {
this.text = res;
});
}
}
Run Code Online (Sandbox Code Playgroud)
public get(key:string,
defaultValue?:string,
variables:Variables = {},
domain?:string):Observable<string>{
const catalog = {
"StackOverflowDomain":
{
"my-key":"my-value"
}
};
return Observable.of(catalog[domain][key]).delay(300);
}
Run Code Online (Sandbox Code Playgroud)
用Variables
:
export interface Variables {
[key:string]:any;
}
Run Code Online (Sandbox Code Playgroud)
describe("I18n component", () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers : [
I18n,
{
provide : I18N_CONFIG,
useValue: {
defaultLocale : "fr_FR",
variable_start: '~',
variable_end : '~'
}
},
{
provide : I18N_LOADERS,
useClass: MockLocaleLoader,
multi : true
}
],
declarations: [
I18nComponent
]
});
fixture = TestBed.createComponent<I18nComponent>(I18nComponent);
comp = fixture.componentInstance;
});
fit("can call I18n.get.", fakeAsync(() => {
comp.content.nativeElement.innerHTML = "nope";
comp.key = "test";
comp.domain = "test domain";
comp.ngOnChanges();
tick();
fixture.detectChanges();
expect(comp.text).toBe("test value");
}));
});
Run Code Online (Sandbox Code Playgroud)
测试失败并显示以下消息:
预期未定义为"测试值".
错误:1个周期性计时器仍在队列中.
因为i18n.get
在检查断言之前没有完成它的工作,所以comp.text仍然是undefined
.
tick
方法调用中添加一个非常高的值,什么都没改变(试过5000).ngOnChanges
返回Promise<void>
,经过正确的解决this.text = res;
和改变fakeAsync
了使用一个简单的测试区done
在caled方法then
的comp.ngOnChanges
.它有效,但ngOnChanges
不应该返回Promise
,我想要一个干净的解决方案.请注意,async
和fakeasync
并不像jasmine.done
从(在撰写本文时)获取确切的注释: https ://angular.io/guide/testing#component-fixture
它说:
使用 did 编写测试函数,虽然比 async 和 fakeAsync 更麻烦,但却是一种可行且偶尔必要的技术。例如,在测试涉及intervalTimer的代码时,您不能调用async或fakeAsync,这在测试async Observable时很常见
归档时间: |
|
查看次数: |
5344 次 |
最近记录: |