typescript - hur man skriver testdata för att få värdet från en tjänst i Angular
Jag har kunduppgifter som customerName och jag måste använda det på två sidor, så jag använder getter och setter i servicefilen. Jag sätter customerName i service (komponent 1) och hämtar det där det behövs (komponent 2), men stöter på fel när jag skriver testfall (komponent 2) för att hämta värdet (i komponent 2).
jag har försökt som nedan
const customerSpy = jasmine.createSpyObj('customerService', ['getCustomerName', 'setCustomerName']);
it('should tests save customer name function', () => {
customerSpy.setCustomerName('xxx'); - I have tried to adding like this
let response = {
'response': 'success'
};
customerSpy.saveCustomerName.and.returnValue(of(response));
fixture.detectChanges();
component.saveCustomerName();
});
Spec-fil:
const customerSpy = jasmine.createSpyObj('customerService', ['getCustomerName', 'setCustomerName', 'saveCustomerName']);
it('should tests save customer name function', () => {
let response = {
'response': 'success'
};
customerSpy.saveCustomerName.and.returnValue(of(response));
fixture.detectChanges();
component.saveCustomerName();
});
komponentkod:
komponent 1:
public dummyFunc(){
this.customerService.setCustomerName('xxx');
}
komponent 2:
public saveCustomerName() {
let name = this.customerService.getCustomerName();
this.customerService.saveCustomerName(name).subscribe(
(success) => {
},
(fail) => {
}
);
}
När jag kör testfallet för komponent 2 bör jag få kundens namn i komponent 2 för att skicka det till mocktjänsten
Svar #1
Du behöver inte oroa dig för component1 när du testar component2. Du kan isolera det för följande funktion som:
public saveCustomerName() {
this.showSpinner = true;
let name = this.customerService.getCustomerName();
this.customerService.saveCustomerName(name).subscribe(
(success) => {
this.showSpinner = false; // or something similar variable assignment.
},
(fail) => {
}
);
}
och i spec-filen:
it('should set customer name on calling function "saveCustomerName()"', () => {
spyOn(component.customerService,'getCustomerName').and.returnValue('testName');
spyOn(component.customerService,'saveCustomerName').and.returnValue(of('saved'));
component.showSpinner = true;
component.saveCustomerName();
expect(component.customerService.getCustomerName).toHaveBeenCalled();
expect(component.customerService.saveCustomerName).toHaveBeenCalledWith('testName);
expect(component.showSpinner).toBeFalsy();
});
