如何在 angular unittest 中发送请求之前验证正文
How to verify the body before sending the request in angular unittest
我在做单元测试时遇到了一些困难,我看了很多文章,但是 none 对我有帮助,似乎很难做一个简单的测试。
我需要测试这个功能,它 returns 和 Observable
,我实际上只需要验证 myBody
是否正确构建,我不想做一个实际的HttpRequest
.
public myCoolFunction(params) {
const myBody= new buildMyBodyModel();
this.buildMyBody(params, myBody); // private function, will set the values for me
return this.sendService.send(myBody); // make a htppPostRequest and returns to me a Observeble
}
private buildMyBody(params, myBody){
myBody.name = params.name;
myBody.color = params.customColor;
myBody.count = params.number + 1;
}
预期 myBody
:
{
name = 'Jack';
color = 'Orange';
count = 4;
}
希望这就是您要找的:-
it('send method should be called with expected param', () => {
const sendService = TestBed.get(SendService);
const params = { name: 'Jack', customColor: 'Orange', number: 3 };
spyOn(sendService, 'send');
component.myCoolFunction(params);
expect(sendService.send).toHaveBeenCalledWith({ name: 'Jack', color: 'Orange', count: 4 });
});
如果你只需要测试你的 myBody 是否构建正确,试试这个:-
it('buildMyBody should change myBody according to params', () => {
const myBody= new buildMyBodyModel();
const params = { name: 'Jack', customColor: 'Orange', number: 3 };
(component as any).buildMyBody(params, myBody);
expect(myBody).toEqual({ name: 'Jack', color: 'Orange', count: 4 });
});
我在做单元测试时遇到了一些困难,我看了很多文章,但是 none 对我有帮助,似乎很难做一个简单的测试。
我需要测试这个功能,它 returns 和 Observable
,我实际上只需要验证 myBody
是否正确构建,我不想做一个实际的HttpRequest
.
public myCoolFunction(params) {
const myBody= new buildMyBodyModel();
this.buildMyBody(params, myBody); // private function, will set the values for me
return this.sendService.send(myBody); // make a htppPostRequest and returns to me a Observeble
}
private buildMyBody(params, myBody){
myBody.name = params.name;
myBody.color = params.customColor;
myBody.count = params.number + 1;
}
预期 myBody
:
{
name = 'Jack';
color = 'Orange';
count = 4;
}
希望这就是您要找的:-
it('send method should be called with expected param', () => {
const sendService = TestBed.get(SendService);
const params = { name: 'Jack', customColor: 'Orange', number: 3 };
spyOn(sendService, 'send');
component.myCoolFunction(params);
expect(sendService.send).toHaveBeenCalledWith({ name: 'Jack', color: 'Orange', count: 4 });
});
如果你只需要测试你的 myBody 是否构建正确,试试这个:-
it('buildMyBody should change myBody according to params', () => {
const myBody= new buildMyBodyModel();
const params = { name: 'Jack', customColor: 'Orange', number: 3 };
(component as any).buildMyBody(params, myBody);
expect(myBody).toEqual({ name: 'Jack', color: 'Orange', count: 4 });
});