如何测试条件是否与茉莉花和角

时间:2018-12-07 07:29:00

标签: angular testing jasmine

我在测试茉莉花时遇到问题,无法测试是否有条件。当我在声纳库运行时,只是有条件无法检测到。

这是我的代码:

login() {
    this.submitted = true;
    this.isLoading = true;

        if (this.loginForm.valid) {
          this.authenticationService
            .login(this.f.username.value, this.f.password.value)
            .pipe(finalize(() => {
              this.loginForm.markAsPristine();
              this.isLoading = false;
            }))
            .subscribe(credentials => {
              this.router.navigate(['/'], { replaceUrl: true });
            }, error => {
              this.error = error;
            });
          this.isLoading = false;
        }
      }

这是我的测试代码:

test('testing conditional if', () => {
    component.loginForm.controls['username'].setValue('admin');
    component.loginForm.controls['password'].setValue('12345678');
    expect(component.loginForm.valid).toBeTruthy();
    spyOn(authenticationService, 'login').and
      .returnValue(component.loginForm.markAsPristine());
    expect(component.login().loginForm.isLoading).toBeFalsy();
    component.login();
  });

帮助我解决我的问题,我在每个网站中搜索但无法解决此问题。感谢您的关注和解决方案。

1 个答案:

答案 0 :(得分:0)

认为问题是spyOn(authenticationService, 'login').and .returnValue(component.loginForm.markAsPristine());,如果您窥探它并返回一个值,那么实际上是在嘲笑它。因此,该函数将被存根,并且仅返回component.loginForm.markAsPristine()的结果 从jasmine docs

  

茉莉具有双重测试功能,称为间谍。间谍可以对任何函数进行存根并跟踪对该函数以及所有参数的调用。

由于您希望为SonarCube执行该函数,但仍然出于跟踪调用的目的而使用间谍程序,因此您应该使用callThrough

spyOn(authenticationService, 'login').and.callThrough(); 来自文档:

  

通过将间谍与and.callThrough链接起来,间谍仍将跟踪对它的所有调用,但除此之外,它将委派给实际的实现。

现在,这将在声纳立方体中注册,因为将执行代码,并且如果将this.loginForm.valid设置为true,则if将执行,并且当设置为false时,{ {1}}部分代码将执行