【问题标题】:Mock Router and Ngzone in Angular 7 Jest Unit testAngular 7 Jest 单元测试中的模拟路由器和 Ngzone
【发布时间】:2020-03-19 13:06:51
【问题描述】:

我在组件类中使用了 ngzone 和路由器。 我的单元测试工作正常,但现在出现错误无法读取未定义的 toLowerCase()。 谁能建议我如何模拟 Ngzone 和路由器。

【问题讨论】:

    标签: jestjs angular7 ngzone


    【解决方案1】:

    我为此使用 TestBed :)

    只需使用您的组件和路由配置您的测试模块,然后从测试模块中获取您的 Router 实例,然后您可以监视 Router.navigate 以使用您的自定义模拟实现。

    
    import { async, ComponentFixture, TestBed } from '@angular/core/testing';
    import { Router } from '@angular/router';
    import { RouterTestingModule } from '@angular/router/testing';
    
    let component: YourComponent;
    let fixture: ComponentFixture<YourComponent>;
    let router: Router;
    
    beforeEach(async(() => {
      TestBed.configureTestingModule({
        imports: [
          RouterTestingModule.withRoutes([
            { path: "", component: YourComponent },
            { path: "**", redirectTo: "" },
          ]),
        ],
        declarations: [YourComponent],
        providers: [],
      }).compileComponents();
    }));
    
    beforeEach(() => {
        fixture = TestBed.createComponent(YourComponent);
        component = fixture.componentInstance;
        router = TestBed.inject(Router);
        jest
          .spyOn(router, 'navigate')
          .mockImplementation(() => of(true).toPromise());
      });
    

    【讨论】:

      猜你喜欢
      • 2022-06-23
      • 1970-01-01
      • 1970-01-01
      • 2019-09-15
      • 2020-07-14
      • 2017-02-09
      • 1970-01-01
      • 2021-10-13
      • 2019-09-08
      相关资源
      最近更新 更多