我正在尝试测试一个组件,该组件在模板中使用routerLink (在使用RouterTestingModule的测试中处理),并在ts文件中使用getCurrentNavigation(),以获取有关nav状态的信息。
我试着只使用RouterTestingModule,但是我不能为getCurrentNavigation()模拟任何东西
我尝试过使用存根类,但这太复杂了,因为我基本上是在模拟整个Router (使用ts-mockito)。
下面是我的代码(注释代码不起作用):
import { async, ComponentFixture, TestBed } from '@angular/core/testing'
import { ErrorsComponent } from './errors.component'
import { RouterTestingModule } from '@angular/router/testing'
import { Router, UrlTree, Navigation } from '@angular/router'
import { mock, when } from 'ts-mockito'
//*** trying to stub Router and all its intricacies ***
// export type Trigger = 'imperative' | 'popstate' | 'hashchange'
// class RouterStub implements Router {
// getCurrentNavigation() {
// return {
// id: 1,
// initialUrl: 'test.com',
// extractedUrl: mock(UrlTree),
// trigger: 'imperative' as Trigger,
// previousNavigation: null,
// extras: {
// state: {
// http: false,
// type: null
// }
// }
// }
// }
// }
fdescribe('ErrorsComponent', () => {
//*** trying ts-mockito for mocking the Router and manually setting getCurrentNavigation ***
let mockRouter = mock(Router)
let mockNavigation: Navigation = {
id: 1,
initialUrl: 'test.com',
extractedUrl: mock(UrlTree),
trigger: 'imperative' as Trigger,
previousNavigation: null,
extras: {
state: {
http: false,
type: null
}
}
}
when(mockRouter.getCurrentNavigation()).thenReturn(mockNavigation)
let router: Router
let component: ErrorsComponent
let fixture: ComponentFixture<ErrorsComponent>
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
ErrorsComponent
],
imports: [
RouterTestingModule
],
providers: [
//*** have tried both useClass and useValue here ***
{ provide: Router, useClass: mockRouter }
]
})
.compileComponents()
router = TestBed.get(Router)
// router.initialNavigation()
}))
beforeEach(() => {
fixture = TestBed.createComponent(ErrorsComponent)
component = fixture.componentInstance
//*** here I tried to brute force the setting of getCurrentNavigation ***
// Object.defineProperty(router, 'getCurrentNavigation()', {writable: true})
// router.getCurrentNavigation().extras = { state: {http: false, type: 'this'}}
// spyOn(router, 'getCurrentNavigation').and.returnValue({'extras': {state: {http: false, type: 'hello'}}})
// router.getCurrentNavigation().extras.state = {http: false, type: 'this'}
fixture.detectChanges()
})
it('should create', () => {
expect(component).toBeTruthy()
})
//*** took this from another stackoverflow but doesn't seem to make any difference ***
afterEach(() => {
TestBed.resetTestingModule();
})
})任何帮助都是非常感谢的!
发布于 2020-02-22 04:15:38
在您的例子中,您使用的是类的一个实例,所以当您创建一个模拟类时,您可以这样做:
providers: [
{ provide: Router, useClass: RouterStub }
]如果你想使用你的变量,你可以使用:
providers: [
{ provide: Router, useFactory: () => mockRouter }
]https://stackoverflow.com/questions/60345102
复制相似问题