首页 > 解决方案 > 单元测试在函数完成之前断言

问题描述

我有一个单元测试,当它在某个时候被标记为真时应该断言一个值

  it('should tick invalidLogin at error on login', () => {
    var checker;
    var targetObj = new Proxy(component, {
      set: (target, key, value) => {
        if (key == 'invalidLogin' && value == true) {checker = true;}
        return true;
      }
    })
    targetObj.onSubmit(); // empty form should cause error
    expect(checker).toBeTruthy();
  });

但问题是断言发生在属性被标记之前。我怎样才能做到这一点,以便断言之后?

这是标记属性的函数

  onSubmit(){
    if (this.loginform.invalid) {
      return;
    }
    this.isSubmitted = true;
    
    const _id = this.f.username.value
    const _pass = this.f.password.value

    this.authService.login(_id, _pass)
      .pipe(first())
      .subscribe(
        data => {
          this.authService.checkAdmin().subscribe(data => {
            if(this.authService.IsCurrentUserAdmin) this.router.navigate(['admin'])
          });
        },
        error => {
          if(error['status']== 400) this.invalidLogin = true;
          console.log(error)
        },
        () => {
          this.isSubmitted = false;
          
        });
        return
    }

更新 我放弃了这个方法,而是使用 Spy 模拟了 onSubmit() 方法,所以我可以在不通过服务的情况下标记属性。

  it('should tick invalidLogin at error on login', () => {
    let button = fixture.debugElement.query(By.css('#form-login')).nativeElement;
    spyOn(component,'onSubmit').and.callFake(() => {
      component.invalidLogin = true;
    })
    button.click();
    fixture.detectChanges();
    let message = fixture.debugElement.query(By.css('#invalid-text')).nativeElement;
    expect(message).toBeTruthy;
  });

标签: angularrxjsjasmineangular-test

解决方案


推荐阅读