Angular Karma Mock错误响应

时间:2017-12-22 06:08:31

标签: angular karma-jasmine

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

it('form submit fail', () => {
    expect(element.querySelector('#login-email')).toBeDefined();
    expect(element.querySelector('#login-password')).toBeDefined();
    updateForm('test@gmail.com', '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:无法读取属性&?39; localizationKey'未定义的

然后发生状态!= 400

2 个答案:

答案 0 :(得分:1)

使用 spyOn

解决了这个问题

spyOn httpMock 类似(但是为了调用某些功能),这里有一个例子:

it('form submit fail', () => {
    email.value = 'test@test.test';
    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()

答案 1 :(得分:0)

手动拨打fixture.detectChanges()

it('form submit fail', () => {
    fixture.detectChanges();
    expect(element.querySelector('#login-email')).toBeDefined();
    expect(element.querySelector('#login-password')).toBeDefined();
    updateForm('test@gmail.com', '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');
  });