Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

angular - Running jasmine tests for a component with NgZone dependency

How would I go ahead with running a jasmine test for the following component:

@Component({
  moduleId: module.id,
  selector: "testComp",
  template: "<div>{{value}}</div>",
})
export class TestComp {
  public value: string = "This is me";
  constructor(public zone: NgZone) {
    this.zone.run(() => console.log("zone is here"));
  }
}

The following fails with the Can't resolve all parameters for NgZone:

describe("test", () => {
    let fixture;
    let component;

beforeEach(async(() => {
    TestBed.configureTestingModule({
        declarations: [TestComp],
        schemas: [NO_ERRORS_SCHEMA],
        providers: [NgZone]
    }).compileComponents;
}));
beforeEach(() => {
    fixture = TestBed.createComponent(TestComp);
    component = fixture.debugElement.componentInstance;
});
it("should check that the component is created", () => {
    expect(component).toBeTruthy();
});

})

using Angular 4.1.3. I found the MockNgZone class @ https://no-shadow-angular-io.firebaseapp.com/docs/ts/latest/api/core/testing/MockNgZone-class.html. But it seems unavailable in the @angular/core/testing for this particular version: enter image description here

Anybody knows what I should do to test this component?

Regards

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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());

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...