[英]Angular Version 14: Getting 'pokemons' array of a trainer
早上好!
这些天我一直在做一个基于口袋妖怪的项目。
我现在要解决的问题是解决位于服务中的函数,该函数获取训练师的 pokemons 数组(下面的函数):
getPokemonsOfATrainer(nombreEntrenador: string){
return this.http.get<Trainer>(`${this.apiUrl1}?fullName=${nombreEntrenador}`).pipe(
map( (entrenador: Trainer) => {
return entrenador.pokemons;
})
);
}
我模拟的 JSON(1 位培训师的示例)采用以下格式:
{
"entrenadores": [
{
"fullName": "Alecs",
"pokemons" : [
{
"name":"Venusaur",
"nature": "Calm",
"attacks": [
{
"name":"Leech Seed",
"type":"Grass",
"style":"Attack"
},
{
"name":"Sleep Powder",
"type":"Grass",
"style":"Support"
},
{
"name":"Grass Knot",
"type":"Grass",
"style":"Attack"
},
{
"name":"Sludge Bomb",
"type":"Poison",
"style":"Attack"
}
]
},
{
"name": "Skarmory",
"nature": "Impish",
"attacks": [
{
"name": "Slash",
"type": "Normal",
"style": "Attack"
},
{
"name": "Spikes",
"type": "Bug",
"style": "Support"
},
{
"name": "Brave Bird",
"type": "Flying",
"style": "Attack"
},
{
"name": "Rock Slide",
"type": "Rock",
"style": "Attack"
}
]
},
{
"name": "Registeel",
"nature": "Careful",
"attacks": [
{
"name": "Focus Blast",
"type": "Fighting",
"style": "Attack"
},
{
"name": "Hyper Beam",
"type": "Normal",
"style": "Attack"
},
{
"name": "Shadow Claw",
"type": "Dark",
"style": "Attack"
},
{
"name": "Rock Smash",
"type": "Rock",
"style": "Attack"
}
]
},
{
"name": "Uxie",
"nature": "Impish",
"attacks": [
{
"name": "Future Sight",
"type": "Psychic",
"style": "Support"
},
{
"name": "Memento",
"type": "Normal",
"style": "Support"
},
{
"name": "Dazzling Gleam",
"type": "Psychic",
"style": "Support"
},
{
"name": "Drain Punch",
"type": "Fighting",
"style": "Attack"
}
]
},
{
"name": "Gallade",
"nature": "Adamant",
"attacks": [
{
"name": "Hypnosis",
"type": "Psychic",
"style": "Support"
},
{
"name": "Night Slash",
"type": "Ghost",
"style": "Attack"
},
{
"name": "Brick Break",
"type": "Fighting",
"style": "Attack"
},
{
"name": "Close Combat",
"type": "fighting",
"style": "Support"
}
]
}
]
}
]
}
是否存在获得训练师口袋妖怪的正确方法?
提前致谢!
您应该使用HttpClientTestingModule
并遵循如何存根 http 请求响应的标准方法。 例如,这个: https ://ng-mocks.sudo.eu/guides/http-request
您的测试可能如下所示:
describe('suite', () => {
beforeEach(() => TestBed.configureTestingModule({
imports: [HttpClientTestingModule], // <- add
providers: [PokemonService],
}).compileComponents());
it('test', () => {
// getting the service and httpMock
const service = TestBed.inject(PokemonService);
const httpMock = TestBed.inject(HttpTestingController);
// subscribing to the result of the http request
let actual: any;
service.getPokemonsOfATrainer('trainer')
.subscribe(value => actual = value);
// stubbing the http request
const req = httpMock.expectOne('<PUT_HERE_API_URL>?fullName=Alecs');
expect(req.request.method).toEqual('GET');
req.flush(mockedJson.entrenadores);
httpMock.verify();
// asserting that we got what expected
expect(actual).toEqual(mockedJson.entrenadores.pokemons);
});
});
问题未解决?试试以下方法:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.