fakeAsync不等待异步操作完成

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)

I18n.get

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方法thencomp.ngOnChanges.它有效,但ngOnChanges不应该返回Promise,我想要一个干净的解决方案.

Nyl*_*ile 6

请注意,asyncfakeasync并不像jasmine.done

从(在撰写本文时)获取确切的注释: https ://angular.io/guide/testing#component-fixture

它说:

使用 did 编写测试函数,虽然比 async 和 fakeAsync 更麻烦,但却是一种可行且偶尔必要的技术。例如,在测试涉及intervalTimer的代码时,您不能调用async或fakeAsync,这在测试async Observable时很常见