I am learning how to test with Spectator the following component:
export class CreateRecipeComponent implements OnInit {
public constructor(private recipeService: RecipeService , private toastr: ToastrService, private router: Router){
}
ngOnInit(): void {}
onReceivingRecipe(recipe:Recipe){
this.recipeService.addRecipeAndSnap(recipe).pipe(take(1)).subscribe({
next: (res) => { this.onCreatedSuccess(res)},
error: (err) => { this.onCreatedFailed(err)}
})
}
onCreatedSuccess(res){
this.router.navigate(["/home"])
this.toastr.success("A recipe has been created","Creating a recipe")
return res
}
onCreatedFailed(err){
this.toastr.error("There has been an error with creating recipe ","Creating a recipe")
return err
}
}
And my current test:
describe('CreateRecipeComponent', () => {
let spectator: Spectator<CreateRecipeComponent>;
let recipeSnapshot: RecipeSnapshot = new RecipeSnapshot("dummy_parentId", "dummy_recipe", "dummy_description","dummy_userId")
let recipeForm: RecipeFormComponent | null;
const createComponent = createComponentFactory({
component: CreateRecipeComponent,
shallow: true,
declarations: [
MockComponents(
RecipeFormComponent
)
],
providers: [mockProvider(RecipeService), mockProvider(ToastrService), mockProvider(Router)]
})
beforeEach( () => {
spectator = createComponent();
spectator.inject(RecipeService).addRecipeAndSnap.and.returnValue(spectator.component.onCreatedSuccess) //Or onCreatedFailed
recipeForm = spectator.query(RecipeFormComponent)
})
it('should render app form', () => {
if (!recipeForm){
throw new Error('recipeForm not found')
}
expect(recipeForm).toBeTruthy()
})
it('should receive a recipe and add recipe and snap', () => {
let recipe = new Recipe("dummy_recipe","dummy_description","dummy_userId")
recipeForm.recipeReceived.emit(recipe)
spectator.detectChanges();
const recipeService = spectator.inject(RecipeService)
expect(recipeService.addRecipeAndSnap).toHaveBeenCalledWith(recipe)
expect(spectator.component.onCreatedSuccess).toHaveBeenCalled()
})
});
What I am trying to figure out is how to mock the onCreatedSuccess function and how to test that function has been called when the addRecipeAndSnap method has been called?
Do I have to use jasmineSpy? I imagine is similar to mocking RecipeService method but I coould not figure it out.