[英]How do i mock a list of Key,Value pairs (in angular) which does not have indices?
I am unit testing an angular application using Jasmine and i am in it. 我使用Jasmine进行单元测试角度应用程序,我就在其中。 The application has a back-end written in Spring boot , which exposes some API's. 该应用程序有一个用Spring引导编写的后端,它暴露了一些API。
The content received from one of the API's (GET request) is a List of Mapped Key,Value(Object,Value) pairs . 从API之一(GET请求)接收的内容是映射密钥,值(对象,值)对的列表 。
What i want is to mock the response such that it looks the same as below (result). 我想要的是模拟响应,使其看起来与下面(结果)相同。
Like this => [
key: value *//does not have an index*
]
Accessed like this => this.list = result['someList'];
For example, 例如,
constructor(private httpClient: HttpCLient) {}
ngOnInit() {
this.getAll().subscribe(result => {
this.someListInsideResult = result['someList'];
console.log('result: ', result);
console.log('someListInsideResult: ', someListInsideResult);
}
}
getAll() {
this.headers = new HttpHeaders().set('X-Authorization', 'Bearer ' + token).set('X-Requested-With', 'XMLHttpRequest').set('Content-Type', 'application/json');
return httpClient.get(url, {headers: headers});
}
console: 安慰:
// actual respose(result)
result: [
key1: value1
key2: value2
...
...
someList: 0: "stringValue"
1: "ENUM"
2: null
]
// list inside the response
someListInsideResult: 0: "stringValue"
1: "ENUM"
2: null
if anyone can help that will very grateful. 如果有人能帮助那将非常感激。
thanks in advance. 提前致谢。
Move the http call to a service, Lets say UserService
: 将http调用移动到服务,让我们说UserService
:
UserService.service.ts UserService.service.ts
export class UserService{
getAll(): Observable<any> {
this.headers = new HttpHeaders().set('X-Authorization', 'Bearer ' + token).set('X-
Requested-With', 'XMLHttpRequest').set('Content-Type', 'application/json');
return httpClient.get(url, {headers: headers});
}
}
In Controller, inject the service and use as 在Controller中,注入服务并使用as
User.component.ts User.component.ts
ngOnInit() {
this.userSvc.getAll().subscribe(result => {
this.someListInsideResult = result['someList'];
console.log('result: ', result);
console.log('someListInsideResult: ', someListInsideResult);
}
}
Then for testing create a mock service: 然后测试创建一个模拟服务:
MockUserService.ts MockUserService.ts
export class MockUserService {
getAll() {
return of({
key1: 'key1',
someList : [{ "0" : "stringValue"}]
})
}
}
then in User.component.spec.ts 然后在User.component.spec.ts中
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [],
declarations: [UserComponent],
providers: [
{ provide: UserService, useClass: MockUserService }] // <-- Here we have injected our Mock
}).compileComponents();
}));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.