gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 18:35:18 24 4
gpt4 key购买 nike

我有一个客户详细信息,如 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com