【问题标题】:Angular 2 Testing: What's the correct way for async testing?Angular 2 测试:异步测试的正确方法是什么?
【发布时间】:2016-09-29 22:36:08
【问题描述】:

我在 Angular 2 项目中使用 karma 和 jasmine 进行了以下测试:

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

【问题讨论】:

    标签: javascript asynchronous angular karma-jasmine


    【解决方案1】:

    区域被创建inside the async method。所以你的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();
      };
    }));
    

    【讨论】:

    • 谢谢,也许我的例子不是那么好。 “a”实际上是对视频标签的引用,“test()”是它的“onplay”函数。所以我想我不能在该区域移动 onplay 的调用,因为它是由视频本身触发的,对吗?我必须在这里“完成”还是有异步/区域的解决方案?
    • 我不知道。我真的没有任何测试视频的经验,我不完全确定你的意思。如果您发布一个真实的示例,也许我可以使用它:-)
    • 抱歉,我尝试创建一个 plunker,但无法让它运行。但是您的提示呼叫者也需要在该区域中帮助我理解了它。最后我只使用了 done only 并且它有效。
    猜你喜欢
    • 1970-01-01
    • 2018-12-03
    • 2021-06-14
    • 1970-01-01
    • 2018-05-17
    • 2019-01-12
    • 1970-01-01
    • 2021-04-15
    • 2021-03-24
    相关资源
    最近更新 更多