angular - 如何编写模拟数据以从角度服务中获取价值
问题描述
我有一个像 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 中获取客户名称以将其传递给模拟服务
解决方案
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();
});
推荐阅读
- javascript - 如何在 chromebook 上使用 javascript 库?
- httprequest - 是否应该使用来自服务器的错误代码来响应为用户自动执行的每天一次的操作以供进一步尝试?
- android - 如何使用 Flutter 从网站上抓取图像?
- wordpress - 如何根据位置自动为我的 Wordpress 网站推荐语言?
- django - Django 消息框架 - 默认情况下缺少 i18n
- html - 如何在选择下拉列表中使用 Angular 9 的选定值
- winmerge - 如何将 prediffer 应用到 WinMerge 以使其在 diff 中的所有文件上运行?
- excel - 将变体转换为字符串
- java - 在java中将20分钟添加到数字
- python - Tensorflow 2.0:使用 Reshape 进行形状推断返回无维度