我正在尝试测试一个从 Activated 路由读取 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();
});
});