jasmine window.location.reload in ngOnDestroy



public ngOnDestroy(): void { window.location.reload(); }

我如何对它进行单元测试?我找到的所有答案都不起作用,或者只有当测试是唯一执行的测试时才起作用。看起来jasmine本质上是在测试套件范围之外调用ngOnDestroy()。mock ngOnDestroy()并将console.log写入实际的东西中也总是会导致控制台输出。

规格:

  • karma-jasmine: 4.0.2
  • jasmine-core: 4.0.0
  • 角:12

为了完成,我尝试了以下操作:

(也检查了beforeAll(), afterEach()和afterAll()中的所有可能性)

  • 模拟ngOnDestroy ():

    beforeEach(() => {
    fixture = TestBed.createComponent(Component);
    fixture.componentInstance.ngOnDestroy = () => null,
    }
    
  • spyOn ngOnDestroy ():

    beforeEach(() => {
    fixture = TestBed.createComponent(Component);
    spyOn(fixture.componentInstance, 'ngOnDestroy').and.callFake(() => null);
    }
    
  • spyOn fixture.destroy ():

    beforeEach(() => {
    fixture = TestBed.createComponent(Component);
    spyOn(fixture, 'destroy').and.callFake(() => null);
    
  • spyOn组件函数:

    // component:
    public ngOnDestroy(): void { this.reload(); }
    public reload(): void { window.location.reload; }
    // test:
    beforeEach(() => {
    fixture = TestBed.createComponent(Component);
    spyOn(fixture.componentInstance, 'reload').and.callFake(() => null);
    
  • spyOn重载:

    beforeEach(() => {
    fixture = TestBed.createComponent(Component);
    spyOn(window.location, 'reload').and.callFake(() => null);
    
  • 模拟重载:

    beforeEach(() => {
    fixture = TestBed.createComponent(component);
    window.location.reload = () => null,
    
  • 模拟位置(这一个给出狂野的结果…):

    beforeEach(() => {
    fixture = TestBed.createComponent(Component);
    window.location = {reload: () => null};
    

window是您的依赖项,因此,它应该像任何其他依赖项一样注入,例如,作为令牌:

export const WINDOW = new InjectionToken('WINDOW');

那么,在Component模块中,你需要提供它:

@NgModule({
// ...
providers: [
{
provide: WINDOW,
useValue: window,
},
],
// ...
})

然后,把它注入到你的Component中,你需要把它作为依赖注入:

export class Component {
constructor(@Inject(WINDOW) private window: Window) {}
public ngOnDestroy(): void {
this.window.location.reload(); // add this.
}
}

现在,您可以在测试中模拟它:

beforeEach(() => {
return TestBed.configureTestingModule({
declarations: [Component],
providers: [
{
provide: WINDOW,
useValue: {
location: {
reload: () => undefined, // or a spy
},
},
},
],
}).compileComponents();
});

利润!

最新更新