【问题标题】:How to verify the body before sending the request in angular unittest如何在角度单元测试中发送请求之前验证正文
【发布时间】:2020-02-19 12:45:06
【问题描述】:

我在做单元测试时遇到了一些麻烦,我看了很多文章,但没有一篇对我有帮助,似乎很难做一个简单的测试。

我需要测试这个函数,它返回一个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;
}

【问题讨论】:

  • 如果你只想测试 body 是否正确构建,只测试 buildMyBody() 函数不够吗?
  • 嗯,测试私有函数是个好习惯吗?
  • 当然,您应该测试系统中的每个功能。

标签: angular unit-testing http-post karma-jasmine testbed


【解决方案1】:

希望这是您正在寻找的:-

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-04
    • 2019-07-12
    • 2016-10-21
    • 2020-05-02
    • 1970-01-01
    • 2011-05-28
    • 2022-07-20
    相关资源
    最近更新 更多