【问题标题】:Unit testing if condition单元测试条件
【发布时间】:2022-01-28 10:46:19
【问题描述】:

0

我正在编写单元测试,但我有点卡在这种方法上。我有从 formGroup 获取名称的 onClickCheck 方法(我在测试中介绍了这部分),然后检查 data.action 是否等于 NEW 以及名称是否存在,然后执行某些操作。

onClickCheck() { const name = this.formGroup.get('name').value;

if (this.data.action === 'NEW' && name) {
    this.service
        .doSomething(name)
        .pipe(take(1))
        .subscribe((result: any) => {
            this.someVar = result.data.attributes;

            if (this.someVar.isDeleted) {
                this.confirmationDialog(dialogData);
            }
        });
}

} 在我的测试中,我尝试这样做,但出现错误:expect(spy).toHaveBeenCalled() 但调用次数为 0。

const doSomethingSpy = spyOn( 服务, '做一点事' ).and.callThrough();

    component.formGroup.setValue({
        name: 'Test',
        lastName: 'TT2'
    });

    component.data= {
        action: 'NEW',
        item: null
    };

    const name = component.formGroup.get('name').value;

    component.onClickCheck();
    fixture.detectChanges();
    expect(doSomethingSpy ).toHaveBeenCalled();

如何测试这个双重条件 IF 中的代码?

【问题讨论】:

    标签: angular unit-testing if-statement karma-jasmine karma-runner


    【解决方案1】:

    我认为问题是:

    const doSomethingSpy = spyOn(service, 'doSomething').and.callThrough();
    

    即使我们正在调用,这个 observable 似乎也永远不会发射。

    尝试将行更改为:

    spyOn(service, 'doSomething').and.returnValue(of({ data: { attributes: { isDeleted: true } } }); // return whatever you want
    

    这有望为您解决问题或让您走得更远。

    【讨论】:

      猜你喜欢
      • 2013-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-07
      • 1970-01-01
      相关资源
      最近更新 更多