I'm currently trying to simulate an API route within a spy service using Jasmine.
Being relatively new to Angular, Typescript, and Jasmine, I find myself uncertain about where to place my code - whether it should go in the beforeEach
block or in its own it('should do xyz...')
block, and so on.
I presume that I should execute the mock setup within the beforeEach
, but I'm encountering an issue with the payload (details below).
spec.ts:
providers: [
{ provide: MyService, useValue: CommonServiceSpies.createHttpClientSpy()},
]
beforeEach(() => {
fixture = TestBed.createComponent(ManagerComponent);
const myVar = TestBed.inject(MyService) as jasmine.SpyObj<MyService>;
const payload = 123 // I had an object similar to the one from component.ts file, but it doesn't work with the current service setup // The error message received was: "Account of type Observable<{}> is not assignable to param of type 'Observable<number>'"
myVar.GetRemainingAmount.and.returnValue(of(payload)); // Error thrown says: "cannot read property 'and' of undefined"
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
service.ts:
export class MyService {
constructor(
private http: HttpClient
) { }
GetRemainingAmount(request: RemainingAmountRequest): Observable<number> {
return this.http.post<number>('/some-route', request);
}
manager-component.ts:
constructor(
public myService: MyService
) { }
hasRemainingSpend() : void {
const payload: RemainingAmountRequest = {
accountId: this.account.id,
otherId: this.xyz?.id
}
this.myService.GetRemainingAmount(payload).subscribe((response: number) => {
this.warningSpend = response;
if (this.warningSpend < this.rate.value || this.warningSpend == null) {
// call another func
// this is working as expected
}
})
}