[英]Angular: How to use router in angular unit testing
I'm writing a test case in angular.我正在 angular 中编写一个测试用例。 I have written a condition if res.length === 1
redirect to the details page.如果res.length === 1
重定向到详细信息页面,我已经写了一个条件。 ( this.router.navigate(['details', id])
). ( this.router.navigate(['details', id])
)。 I'm getting the id
from the first array of the object in body response as const id = res[0].id
.我从 object 的第一个数组中获取id
作为const id = res[0].id
。 These both line are not covered in my code coverage.这两行都没有包含在我的代码覆盖范围内。 Can anyone let me know where I made mistake?谁能让我知道我在哪里犯了错误?
I'm getting Expected spy navigate to have been called with [ [ '/product-details', 'SAAASD0001' ] ] but it was never called.
我正在Expected spy navigate to have been called with [ [ '/product-details', 'SAAASD0001' ] ] but it was never called.
app.component.spec.ts app.component.spec.ts
let router = {navigate: jasmine.createSpy('navigate')};
TestBed.configureTestingModule({
imports: [RouterTestingModule],
providers: [
{ provide: Router, useValue: router }
]
})
it('should take data from store', () => {
const mockData = [
{
id: '123',
name: 'Stackoverlow',
}
]
expect(component.getList).toEqual(mockData);
const productId = mockData[0].id;
expect(router.navigate).toHaveBeenCalledWith(['/details', id]);
});
app.component.ts app.component.ts
getList() {
this.store
.select('content', 'catalogue')
.pipe(takeUntil(this.onDestroy$))
.subscribe((res) => {
Iif (res.length === 1) {
// this line doesn't cover
const id = res[0].id;
// this line doesn't cover
this.router.navigate(['details', id]);
} else {
this.list = category(res);
}
});
}
Make Router
and Store
public in component and try:在组件中公开Router
和Store
并尝试:
TestBed.configureTestingModule({
imports: [RouterTestingModule],
providers: [Router,Store ]
})
it('should take data from store', () => {
const response = [{id: 'val'}];
spyOn(component.store,"select").and.returnValue(of(response));
spyOn(component.router,"navigate").and.callThrough();
component.getList();
expect(router.navigate).toHaveBeenCalledWith(['/details', response[0].id]);
});
similarly cover else
part by changing const response = [{id: 'val'}];
同样通过更改const response = [{id: 'val'}];
来覆盖else
部分
Add this thing to your imports:将此东西添加到您的导入中:
RouterTestingModule.withRoutes([
{ path: 'path1', component: TestComponent1},
{ path: 'home', component: DashboardComponent }
]),
later on in your test case: you can spy on "Navigate" of Router and and use it for redirection to any component mentioned in imports.稍后在您的测试用例中:您可以监视路由器的“导航”并将其用于重定向到导入中提到的任何组件。
spyOn(Router,"navigate").and.callthrough();
router.navigate([/path1]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.