微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

单元测试在函数完成之前断言

如何解决单元测试在函数完成之前断言

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。