Igor
Igor

Reputation: 408

How to verify the body before sending the request in angular unittest

I having some trouble in making a unit test, I read a lot of articles, but none of them helped me, seems hard to make a simple test.

I need to test this function, it returns an Observable, I actually only need to verify if myBody was build correctly, I don't want to make an actual 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;
}

Expected myBody:

{
    name = 'Jack';
    color = 'Orange';
    count = 4;
}

Upvotes: 1

Views: 818

Answers (1)

Anand Bhushan
Anand Bhushan

Reputation: 783

Hope this is what you're looking for:-

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 });
});

If you only need to test if your myBody is built correctly, try this:-

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 });
});

Upvotes: 1

Related Questions