加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Angular 2,异步测试和setTimeout

发布时间:2020-12-17 18:06:58 所属栏目:安全 来源:网络整理
导读:我有一个关于测试的问题. 我使用Angular 6,业力和茉莉. 我的测试是: it(`my test`,async(() = { console.log('### start test'); fixture.detectChanges(); // call a method which has async code fixture.componentInstance.fakeTimeout(); console.log('
我有一个关于测试的问题.
我使用Angular 6,业力和茉莉.

我的测试是:

it(`my test`,async(() => {
    console.log('### start test');
    fixture.detectChanges();
    // call a method which has async code
    fixture.componentInstance.fakeTimeout();
    console.log('isStable',fixture.isStable());
    fixture.whenStable().then(() => {
        // here I must check smth only when all async operations are completed
        console.log('### end test');
    });
}));

我试图以不同的方式实现fakeTimeout方法,即:

public fakeTimeout() {
    new Promise((resolve,reject) => {
        setTimeout(() => {
            console.log('>>>>>> COMPONENT TIMEOUT!!!');
            resolve(true);
        },2000);
    }).then(() => {});
}

要么

public fakeTimeout() {
    setTimeout(() => {
        console.log('>>>>>> COMPONENT TIMEOUT!!!');
    },2000);
}

在这两种情况下,我都有以下日志:

### start test
isStable true
### end test
>>>>>> COMPONENT TIMEOUT!!!

但是,根据官方文档,whenStable promise只会解析所有异步操作,并且日志必须是:

### start test
isStable true
>>>>>> COMPONENT TIMEOUT!!!
### end test

我做错了什么?如果必须等待所有异步操作完成到我的组件中,我应该如何正确编写异步测试?

解决方法

不确定,为什么fixture.whenStable()不会自己等待延迟(setTimeout).

但它可以正常使用Promise或Observable返回

但你可以解决它的方式:

方法1:您可以使用tick()手动等待使用fakeAync

it(`my test`,fakeAsync(() => {
    console.log('### start test');
    fixture.detectChanges();
    // call a method which has async code
    fixture.componentInstance.fakeTimeout();
    tick(2100); // just more than the delay mentioned inside the component.
    console.log('isStable',fixture.isStable());
    fixture.whenStable().then(() => {
        // here I must check smth only when all async operations are completed
        console.log('### end test');
    });
}));

方法2:在spec文件中有自己的setTimeout并使用done()完成测试

it(`my test`,((done) => {
        console.log('### start test');
        fixture.detectChanges();
        // call a method which has async code
        fixture.componentInstance.fakeTimeout();
        setTimeout(()=> {
          console.log('isStable',fixture.isStable());
          console.log('### end test');
          done();
        },2100)
}));

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读