作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我有一个客户详细信息,如 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/
我是一名优秀的程序员,十分优秀!