angular - 如何编写模拟数据以从 Angular 服务中获取值(value)

标签 angular typescript unit-testing karma-jasmine

我有一个客户详细信息,如 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 中获取客户名称以将其传递给模拟服务

最佳答案

在测试 component2 时,您无需担心 component1。您可以将其隔离用于以下功能:

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

关于angular - 如何编写模拟数据以从 Angular 服务中获取值(value),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57079153/

相关文章:

Typescript:模块作为返回类型?

javascript - Typescript 无效的左手运算符

javascript - 在 TypeScript 中使用相同的 Update 方法添加用户时设置自动 id

ios - OCMock 方法中的 stub block

javascript - 如何用 Jest 模拟node_module内部的构造函数?

javascript - 模板中默认选择 Angular 4 选项

javascript - AES 解密返回空字符串

Python、单元测试和模拟导入

angular - 从映射生成类型/接口(interface)列表

angular - 在运行时定义 BlockUi Angular 注释?