我正在尝试测试从“已激活”路由读取Id参数的组件,目前我的目标是使组件正确呈现,但我不知道测试为什么会失败。
对于相似的组件,我以相同的方式传递了ActivatedRoute,并且在那里工作没有任何问题。
组件:
@Component({
selector: 'app-recipe-detail',
templateUrl: './recipe-detail.component.html',
styleUrls: ['./recipe-detail.component.css']
})
export class RecipeDetailComponent implements OnInit {
recipeState: Observable<fromRecipe.State>;
id: number;
constructor(
private route: ActivatedRoute,
private router: Router,
private store: Store<fromRecipe.FeatureState>
) { }
// pass the "id" to return the index of the array
ngOnInit() {
this.route.params
.subscribe((params: Params) => {
this.id = +params['id'];
this.recipeState = this.store.select('recipes');
});
}
onAddToShopping() {
this.store.select('recipes').pipe(take(1)).subscribe((recipeState: fromRecipe.State) => {
this.store.dispatch(new ShoppingListAction.AddIngredients(recipeState.recipes[this.id].ingredients));
});
}
onEditRecipe() {
this.router.navigate(['edit'], {relativeTo: this.route});
}
onDeleteRecipe() {
this.store.dispatch(new RecipeActions.DeleteRecipe(this.id));
this.router.navigate(['./recipes']);
}
}
规范文件
describe('Recipe Detail Component should', () => {
let fixture: ComponentFixture<RecipeDetailComponent>;
let component: RecipeDetailComponent;
let store: TestStore<any>;
const router = {
navigate: jasmine.createSpy('navigate')
};
let dispatchSpy;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [ RecipeDetailComponent ],
imports: [RouterTestingModule],
providers: [
{provide: Store, useClass: TestStore},
{ provide: Router, useValue: router },
{
provide: ActivatedRoute,
useValue: {
params: of({ id: 0 })
}
}],
}).compileComponents();
});
beforeEach(async(inject([Store], (testStore: TestStore<any>) => {
store = testStore;
testStore.setState({initialState});
fixture = TestBed.createComponent(RecipeDetailComponent);
component = fixture.debugElement.componentInstance;
fixture.detectChanges();
})));
it('render correctly', () => {
console.log(component);
expect(component).toBeTruthy();
});
});
答案 0 :(得分:0)
我遇到了必须使用paramMap解决的类似问题:
providers: [
{ provide: ActivatedRoute, useValue: {
paramMap: of( convertToParamMap( { id: 0 } ) )
}
}
],
convertToParamMap
在@angular/Router
祝你好运
答案 1 :(得分:0)
我有类似的问题,这也是由组件中的 this.route.data.subscribe
引起的。如果有人有类似的问题,最好的调查方法是:在Jasmine中运行测试时,以调试模式检查控制台日志。