简体   繁体   English

如何监视返回 Promise -Angular 的方法

[英]How to spyOn method that returns Promise -Angular

The below method calls CheckLastEmployee method which returns true/false.下面的方法调用返回 true/false 的 CheckLastEmployee 方法。

async nextEmployee(empId:number) {
    let isLast;
    await this.CheckLastEmployee(empId).then(x=>{isLast=x});
    if (isLast) {
        Submit();
    }
}

More logic inside CheckLastEmployee....copied a part of the code.. CheckLastEmployee 中的更多逻辑..复制了部分代码..

async CheckLastEmployee(empId:number){
    let enrollment = new Map<string, boolean>();
    await this.GetEnrolledPrograms().then(res => enrollment = res);
    if(empId==10)
        return true;
    else
        return false;
}

Test case .spec.ts测试用例 .spec.ts

 it('Is Last Employee-submit',()=>{
        spyOn(component,'CheckLastEmployee').and.returnValue(Promise.resolve(true));
        spyOn(component,'Submit');
        component.nextEmployee(10);
        expect(component.Submit).toHaveBeenCalled();
    }

the above test case fails.上述测试用例失败。

I think your test is missing async/await.我认为您的测试缺少异步/等待。 Furthermore, I think in order to be able to see if your submit method was called, you need to spy on that method as well.此外,我认为为了能够查看您的submit方法是否被调用,您还需要监视该方法。 Please try the following implementation to see if it solves your issue:请尝试以下实现,看看它是否能解决您的问题:

it('Is Last Employee-submit', fakeAsync( () => {
    spyOn(component, 'CheckLastEmployee').and.resolveTo(true);
    let spy = spyOn(component, 'submit');  // Spy on submit method
    component.nextEmployee(10);
    tick(); // Try this
    expect(spy).toHaveBeenCalled(); // Now expect the spy to have been called if isLast is defined
}));

In case the above test didnt work, you can try tick(1000) (1000 milliseconds) or another value as well to just see if the test is failing due to a race condition or not.如果上述测试不起作用,您可以尝试tick(1000) (1000 毫秒)或其他值,以查看测试是否由于竞争条件而失败。

Side note:边注:

You need to import tick and fakeAsync :您需要导入tickfakeAsync

import {fakeAsync, tick} from '@angular/core/testing';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM