我在组件类中使用了 ngzone 和路由器。我的单元测试工作正常,但现在出现错误无法读取未定义的 toLowerCase()。谁能建议我如何模拟 Ngzone 和路由器。
问问题
1972 次
1 回答
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());
});
于 2020-05-11T10:37:45.187 回答