[英]Unit testing Angular Router queryParamMap
我希望在 ngOnInit 生命周期中使用Angular queryParamMap 。 目標是將查詢參數從這個組件作為狀態傳遞給另一個。 盡管功能就像魅力一樣,但我無法對代碼功能進行單元測試。
export class AppComponent implements OnInit {
constructor(private readonly route: Router, private router: ActivatedRoute) {}
ngOnInit() {
this.router.queryParamMap.subscribe((resp) => {
const state ={} as any;
state.token = resp.get('token')
state.clientID = resp.get('id')
state.timestamp = resp.get('timeStamp')
this.route.navigate(['/dashboard'],{state})
});
}}
這是我開玩笑的單元測試方法
const activatedRouteMock = {
queryParamMap: of(routes:{token:1,id:2},
test(key){
return this.routes.key
})
};
const mockRoute = mock<Router>();
當我做
it('should be defined', () => {
component.ngOnInit()
expect(mockRoute.navigate).toBeCalledTimes(1)
expect(mockRoute.navigate).toBeCalledWith(['dashboard'], {state:{token:1,id:2}})
});
但我得到錯誤
預期電話 1 已接電話 0
我不確定如何使用 QueryParamMap 對該功能進行單元測試,因為屬性可能為空。
就我而言,我使用 Jest 來實現我的測試。
我的組件構造函數和 ngOnInit 方法如下所示:
constructor(private route: ActivatedRoute){}
ngOnInit(): void {
this.route.queryParamMap.subscribe((params) => {
this.partner = params.get('partner')
}
}
然后在測試文件上,我創建一個帶有模擬 get 函數的 params 對象,並將此設置應用於 beforeEach 方法:
const params = {
get: jest.fn()
}
describe('MyComponent', () => {
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [RouterTestingModule],
declarations: [MyComponent],
providers: [{
provide: ActivatedRoute,
useValue: {
queryParamMap: of(params)
}
}]
})
)
beforeEach(() => {
fixture = TestBed.createComponent(MyComponent)
component = fixture.componentInstance
fixture.detectChanges()
TestBed.inject(ActivatedRoute)
)
}
在我的測試用例中,我監視了我的params
模擬對象的get
函數,因為我在提供程序中設置為在ActivatedRoute.queryParamMap
的可觀察對象中返回該對象:
it('should set the partner property to PARTNER_X as in the GET parameter', () => {
const getParamSpy = jest.spyOn(params, 'get').mockReturnValueOnce('PARTNER_X')
component.ngOnInit()
expect(component.partner).toBe('PARTNER_X')
expect(getParamSpy).toBeCalledWith('partner')
})
要獲得更具體的答案,最好提供有關您的設置的更多詳細信息,否則很難確定您可能面臨的問題是什么。
我希望這會很有用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.