簡體   English   中英

Angular 2測試:異步測試的正確方法是什么?

[英]Angular 2 Testing: What's the correct way for async testing?

我在帶有業力和茉莉的角度2項目中進行了以下測試:

let a: any;

beforeEach(() => {
    a = {};

    setTimeout(() => {
        a.test();
    }, 1000);
});

it('should work with async and promise', async(() => {

   return new Promise((resolve) => {
       a.test = () => {
           console.log('erster test');
           assertThat(true, is(false));
           resolve();
       };
   });
}));

it('should work with async and done', async((done) => {

    a.test = () => {
        console.log('zweiter test');
        assertThat(true, is(false));
        done();
    };
}));

it('should work with done', (done) => {

    a.test = () => {
        console.log('dritter test');
        assertThat(true, is(false));
        done();
    };
});

有效的唯一情況(意味着失敗)是最后一個只有“完成”回調的情況。 對於第二個,我不確定但是第一個不應該是在角度2中測試異步的正確方法嗎? 我想用“異步”你在你的功能周圍放置一個區域,它正在等待返回的承諾? 我試圖理解異步實現,但我沒有得到它: https//github.com/angular/angular/blob/master/modules/%40angular/core/testing/async.ts

該區域被創建內部 async方法 所以你的setTimeout (在beforeEach )不在該區域內。 如果將setTimeout移動到async回調內部 ,那么它就在區域中,並且測試應該按預期工作(意味着等待異步任務完成)。

it('should work with async and promise', async(() => {
  setTimeout(() => {
    a.test();
  }, 1000);
  return new Promise((resolve) => {
    a.test = () => {
      console.log('erster test');
      expect(true).toBe(false);
      resolve();
    };
  });
}));

it('should work with async and done', async((done: Function) => {
  setTimeout(() => {
    a.test();
  }, 1000);
  a.test = () => {
    console.log('zweiter test');
    expect(true).toBe(false);
    done();
  };
}));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM