如何编写模拟数据以从角度获取服务的价值

时间:2019-07-17 15:14:51

标签: angular typescript unit-testing karma-jasmine

我有一个类似于customerName的客户详细信息,我必须在2页中使用它,因此我在服务文件中使用getter和setter,我在service(组件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中获得客户名称,以将其传递给模拟服务

1 个答案:

答案 0 :(得分:0)

在测试{% for group in user.groups.all %} <li><a href="#">{{ group.name }}</a></li> {% endfor %} 时,您不必担心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) => {
      }
    );
  }