【问题标题】:How to wait inside a beforeEach in Angular 4/Jasmine如何在 Angular 4/Jasmine 的 beforeEach 中等待
【发布时间】:2017-11-15 11:23:41
【问题描述】:

我的一个组件在ngOnInit 中使用了 setTimeout,例如:

ngOnInit() {
  setTimeout(() => {
      // do some setup stuff using FormBuilder
  }, 100);
}

在此组件的单元测试中,我需要监视使用 FormBuilder 以编程方式构建的控件之一的方法之一,因此我在 beforeEach 中执行此操作:

describe('testing something', () => {

    beforeEach(() => {
        spyOn(component.form.controls.myControl, 'enable');
    });

    it('does something', () => {
      // test stuff
    });

}); 

在添加超时之前,测试运行良好。如何让beforeEachngOnInit 方法中等待100 毫秒超时?

我尝试将asyncfakeAsync 添加到外部描述中,例如像这样:

 describe('testing something', <any>fakeAsync(() => {
     ...
 }));

describe('testing something', async(() => {
     ...
 }));

但在第一种情况下,fakeAsync 我在测试运行程序中看到一条消息错误:应在“ProxyZone”中运行,但未找到。,在第二种情况下如果它甚至不运行测试。我还尝试将it 方法包装在fakeAsync 中,但这并不能延迟beforeEach

我尝试将beforeEach 中的spyOn 方法包装在setTimeout 中,但这似乎没有任何效果,即测试以同样的方式失败。

我也尝试过将fakeAsyncbeforeEach 一起使用,如下所示:

beforeEach(<any>fakeAsync(() => {
    tick(100);
    spyOn(component.modelForm.controls.myControl, 'enable');

  }));

但这也不起作用。它不会导致任何错误,但我要监视的方法还不存在,即使在滴答声之后也是如此。

如何强制beforeEach 等待ngOnInit() 中的超时?有没有可能?

【问题讨论】:

  • 我知道ngOnInit 中的setTimeout 很糟糕。不幸的是,我无权更改它。
  • 只是为了确定,在 async() 测试中运行时,您是否使用了 whenStable(),而在使用 fakeAsync() 运行时,您是否使用了 tick()?
  • 我没有尝试whenStable,但我确实在beforeEach 中尝试了tick(100),但这并没有帮助
  • 这就是 fakeAsync 的用途,它应该可以按预期工作而无需额外的操作。这可能与测试设置有关。复制它的方法会很有用 - stackblitz.com 或 github 存储库。
  • 但是fakeAsync 是否与describe 而不是it 一起使用?我在同一文件的其他测试中使用fakeAsyncit 方法

标签: javascript angular asynchronous jasmine


【解决方案1】:

如果需要,可以针对 beforeEach 调整以下解决方案

before(() => {
  jasmine.clock().install();
})

after(() => {
  jasmine.clock().uninstall();
})

it('test case', () => {
  spyOn(component.modelForm.controls.myControl, 'enable');
  
  component.ngOnInit();

  var timeout = 2000 // 2 seconds
  jasmine.clock().tick(timeout);

  expect(component.modelForm.controls.myControl.enable).toHaveBeenCalled()
})

【讨论】:

    【解决方案2】:

    我可以在 beforeEach 中使用 Jasmine 的 done 回调来解决此问题,如下所示:

    beforeEach((done) => {
        component.ngOnInit();
    
        setTimeout(() => {
          spyOn(component.modelForm.controls.myControl, 'enable');
    
          done();
        }, 100);
      });
    

    看起来很直观!

    【讨论】:

      猜你喜欢
      • 2014-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-23
      • 2017-12-16
      • 1970-01-01
      • 2018-10-04
      • 1970-01-01
      相关资源
      最近更新 更多