Conflict between zone.js and Jasmine's clock

*爱你&永不变心* 提交于 2020-01-03 07:18:28

问题


I am working with a Jasmine testing suite that includes both "vanilla" Jasmine tests along with Jasmine tests for some Angular 2 components. Because of Angular 2's inclusion, zone.js gets loaded. This creates a conflict with Jasmine's clock. For example, the following test fails with the error, Error: Jasmine Clock was unable to install over custom global timer functions. Is the clock already installed?

describe('an async test with zone.js present', function() {
  beforeEach(function() {
    jasmine.clock().install();
  });

  afterEach(function() {
    jasmine.clock().uninstall();
  });

  it('cannot install jasmine\'s mock clock', function() {
    var callback = jasmine.createSpy('setTimeoutCallback')
    setTimeout(callback, 55);
    jasmine.clock().tick(56);
    expect(callback).toHaveBeenCalled();
  });
})

Here is plunker for above code.

Short of delivering the Angular 2 tests separately from the "vanilla" tests, I am wondering what options might be available. For example, is it possible to perform the Jasmine clock's job with the zone? For example, is it possible to simulate the tick with the zone or flush all of the scheduled tasks before the assertion?


回答1:


For me it works if you uninstall the clock in beforeEach. Its not recommended by jasmine and a bit strange because for uninstall it makes more sense to use afterEach. But calling uninstall before the first install call happens fixed it for me.




回答2:


As stated on Angular documentation you should use tick function in a fakeAsync body which is part of the @angular/core/testing module.

Using your example and TypeScript it would look something like this...

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

...

it('cannot install jasmine\'s mock clock', fakeAsync(() => {
   var callback = jasmine.createSpy('setTimeoutCallback')
   setTimeout(callback, 55);
   tick(56);
   expect(callback).toHaveBeenCalled();
}));



回答3:


The code which throws this here.

It implies that jasmine was loaded before Zone.js. Switch the loading order. Zone always needs to be loaded first.




回答4:


This have been resolved by https://github.com/angular/zone.js/pull/1009. zone.js and future angular will support jasmine.clock().



来源:https://stackoverflow.com/questions/39600819/conflict-between-zone-js-and-jasmines-clock

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!