Angular Karma Mock错误响应

问题描述 投票:0回答:2

测试总是失败,因为login.subscribe错误没有error.status error.status - >'undefined'测试:

it('form submit fail', () => {
    expect(element.querySelector('#login-email')).toBeDefined();
    expect(element.querySelector('#login-password')).toBeDefined();
    updateForm('[email protected]', '123456');
    component.login(component.loginForm);
    httpMock
      .expectOne(`${environment.apiProtocol}://${environment.apiHost}/auth`)
      .error( new ErrorEvent( 'SOME_ERROR', {error: 400}), {status: 400, statusText: ''});
    httpMock.verify();
    expect(component.hasError).toBeTruthy();
    expect(component.error).toEqual('unregisteredPair');
  });

component.login:

login(form: FormGroup): void {
    if (this.lockForm) {
      return;
    }
    if (!form.valid) {
      Object.keys(form.controls).forEach(key => {
        form.get(key).markAsTouched();
      });
      this.lockForm = false;
      return;
    }
    this.lockForm = true;
    this.hasError = false;
    this.error = '';
    this.loading = true;
    this.service.login(form.value.email, form.value.password).subscribe(() => {
      this.router.navigate([this.service.redirectUrl || '/dashboard']);
      this.loading = false;
    }, (error: any) => {
      this.hasError = true;
      this.lockForm = false;
      this.error = error.status === 400 ? 'unregisteredPair' : error.error.localizationKey;
      this.loading = false;
    });
  }

在这个测试结束时得到错误:

TypeError:无法读取未定义的属性“localizationKey”

这发生了然后状态!= 400

angular karma-jasmine
2个回答
1
投票

使用spyOn解决了这个问题

spyOn类似于httpMock(但是为了调用一些函数),这是一个例子:

it('form submit fail', () => {
    email.value = '[email protected]';
    email.dispatchEvent(new Event('input'));
    password.value = '123456';
    password.dispatchEvent(new Event('input'));
    spyOn(service, 'login').and
      .returnValue(
        Observable.throw(
          new HttpErrorResponse({
            error: {
              message: 'Here some message...',
              localizedKey: 'someKey'
            }, 
            status: 500
          })
        )
      );
    button.click();
    expect(component.hasError).toBeTruthy();
    expect(component.lockForm).toBeFalsy();
    expect(component.error).toEqual('someKey');
  });

在此示例中,spyOn模拟来自AuthService.login()的响应(在调用时)并返回单元测试的预期响应

对于成功响应,使用Observable.of()和新的HttpResponse()


0
投票

手动打电话给fixture.detectChanges()

it('form submit fail', () => {
    fixture.detectChanges();
    expect(element.querySelector('#login-email')).toBeDefined();
    expect(element.querySelector('#login-password')).toBeDefined();
    updateForm('[email protected]', '123456');
    component.login(component.loginForm);
    httpMock
      .expectOne(`${environment.apiProtocol}://${environment.apiHost}/auth`)
      .error( new ErrorEvent( 'SOME_ERROR', {error: 400}), {status: 400, statusText: ''});
    httpMock.verify();
    expect(component.hasError).toBeTruthy();
    expect(component.error).toEqual('unregisteredPair');
  });
© www.soinside.com 2019 - 2024. All rights reserved.