Running jasmine tests for a component with NgZone dependency

雨燕双飞 提交于 2019-11-29 14:39:06

It's a bit of a mystery, MockNgZone is still in the source but removed from the public API.

Given the simple implementation of mock run()

export class MockNgZone extends NgZone {
  ...
  run(fn: Function): any { return fn(); }

I would use this to get you over the hump

const mockNgZone = jasmine.createSpyObj('mockNgZone', ['run', 'runOutsideAngular']);
mockNgZone.run.and.callFake(fn => fn());

TestBed.configureTestingModule({
  ...
  providers: [
    { provide: NgZone, useValue: mockNgZone },
  ]

If your problem is about runOutsideAngular because then you cannot use async or fakeAsync, the only thing you need to mock is that function and the following works well:

const ngZone = TestBed.get(NgZone);

spyOn(ngZone, 'runOutsideAngular').and.callFake((fn: Function) => fn());

In Angular 5.2.4 (installed via Angular CLI 1.6.8) the mock was removed from the codebase so there's no need to use it in Jasmine. Just skip the declaration of NgZone in providers list.

We had the same issue, exactly. At the end we left ngZone as is, and make sure we test the callbacks it uses.

beforeEach(async(() => {
TestBed.configureTestingModule({
    ...
    providers: [NgZone]
  })
}));

And for code that used the ngZone such as

zone.run(someFunction)

We made sure to have good test coverage someFunction with unit tests.

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