ค้นหาเว็บไซต์

typescript - วิธีเขียนข้อมูลจำลองเพื่อดึงค่าจากบริการใน Angular


ฉันมีรายละเอียดลูกค้าเช่น customerName ฉันต้องใช้ใน 2 หน้า ดังนั้นฉันจึงใช้ getter และ setter ในไฟล์บริการ ฉันตั้งค่า customerName ในบริการ (component 1) และดึงค่าเมื่อจำเป็น (component 2) พบข้อผิดพลาดขณะเขียนกรณีทดสอบ (component 2) สำหรับการดึงค่า (ใน component 2)

ฉันได้ลองแบบด้านล่าง

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();
    });

ไฟล์สเปค:

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();
    });

รหัสส่วนประกอบ:

ชิ้นส่วน 1:

public dummyFunc(){
  this.customerService.setCustomerName('xxx');
}

ส่วนประกอบ 2:

public saveCustomerName() {
    let name = this.customerService.getCustomerName();
    this.customerService.saveCustomerName(name).subscribe(
      (success) => {

      },
      (fail) => {
      }
    );
  }

ขณะรันเคสทดสอบสำหรับส่วนประกอบ 2 ฉันควรได้รับชื่อของลูกค้าในส่วนประกอบ 2 เพื่อนำไปส่งต่อให้กับ mockservice

คำตอบ #1

คุณไม่จำเป็นต้องกังวลเกี่ยวกับ component1 เมื่อคุณกำลังทดสอบ component2 คุณสามารถแยกมันออกสำหรับฟังก์ชันด้านล่างได้ดังนี้:

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) => {
      }
    );
  }

และในไฟล์สเปก:

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();
});