首页 > 解决方案 > 如何编写模拟数据以从角度服务中获取价值

问题描述

我有一个像 customerName 这样的客户详细信息,我必须在 2 页中使用它,所以我在服务文件中使用 getter 和 setter,我在服务(组件 1)中设置了 customerName,并将它放在需要的地方(组件 2)在编写时遇到错误用于获取值的测试用例(组件 2)(在组件 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 中获取客户名称以将其传递给模拟服务

标签: angulartypescriptunit-testingkarma-jasmine

解决方案


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

推荐阅读