0

我正在尝试测试一个从 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();
  });
});
4

2 回答 2

0

我有一个类似的问题,我必须使用 paramMap 解决:

providers: [
    { provide: ActivatedRoute, useValue: {
            paramMap: of( convertToParamMap( { id: 0 } ) )
        }
    }
],

convertToParamMap@angular/Router

祝你好运

于 2018-10-29T14:39:53.850 回答
0

我有类似的问题,它也是由 this.route.data.subscribe组件引起的。如果有人有类似的问题,最好的调查方法是:在 Jasmine 中运行测试时以调试模式检查控制台日志。

于 2020-12-08T12:43:29.550 回答