Service
export interface ITransferRequest {
serviceName:string;
amount:number
}
@Injectable()
export class TransferService
{
transferMoneyUrl = 'https://localhost:44321/api/TransferService';
constructor(private http:HttpClient){}
doTransfer(transferRequest: ITransferRequest): Observable<TransferResult> {
return this.http.post<TransferResult>(this.transferMoneyUrl, transferRequest).pipe();
}
}
Test Code
describe('AppComponent', () => {
let transferService: TransferService,
mockHttp: any;
beforeEach(async () => {
mockHttp = jasmine.createSpyObj('mockHttp',['get', 'post']);
transferService = new TransferService(mockHttp);
await TestBed.configureTestingModule({
imports: [
RouterTestingModule
],
declarations: [
AppComponent
],
}).compileComponents();
});
it('should do transfer', done => {
const transferRequest: ITransferRequest = { serviceName: "A", amount: 1000 };
mockHttp.get.and.returnValue(of(<TransferResult>{ result : 600 }));
transferService.doTransfer(<ITransferRequest>transferRequest)
.subscribe((x: TransferResult) => {
expect(x.result).toBe(600);
done();
});
});
ERROR
TypeError: Cannot read properties of undefined (reading 'pipe')
at TransferService.doTransfer (http://localhost:9876/_karma_webpack_/webpack:/src/app/services/transfer.service.ts:32:86)
at UserContext.<anonymous> (http://localhost:9876/_karma_webpack_/webpack:/src/app/app.component.spec.ts:35:21)
at _ZoneDelegate.invoke (http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/fesm2015/zone.js:372:1)
at ProxyZoneSpec.onInvoke (http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/fesm2015/zone-testing.js:287:1)
at _ZoneDelegate.invoke (http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/fesm2015/zone.js:371:1)
at Zone.run (http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/fesm2015/zone.js:134:1)
at runInTestZone (http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/fesm2015/zone-testing.js:564:1)
at UserContext.<anonymous> (http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/fesm2015/zone-testing.js:580:1)
at <Jasmine>
CodePudding user response:
First off, the TestBed configuration is totally useless in your sample. Just delete it.
Your bug is because you are providing a mock return value for get
but your method under test calls post
. Because the default return value for spied methods is undefined
it blows up on the .pipe()
with that error.