简体   繁体   English

Angular 7:如何从测试用例访问/发送HTTP响应的正文部分

[英]Angular 7: How to access/send only body part of HTTP Response from test case

I'm creating unit test cases in Angular 7 for a Component with async service . 我正在Angular 7中为具有异步服务Component创建单元测试用例。

here is my component file : 这是我的组件文件:

  submitLoginForm() {
    if (this.loginForm.valid) {
      // send a http request to save this data
      this.guestUserService.login(this.loginForm.value).subscribe(
        result => {
          // if (result) {
          if (result['token']) { // The value of result is coming the complete HttpResponse. 
            localStorage.setItem('authToken', result['token']);
            this.router.navigate(['/dashboard']);
          }
        },
        error => {
          console.log('error', error.message);
          this.router.navigate(['/error']);
        }
      );
    } else {
      this.validateAllFields(this.loginForm);
    }
  }

}

the unit test case: 单元测试用例:

fdescribe('LoginComponent', () => {
    let component: LoginComponent;
    let fixture: ComponentFixture<LoginComponent>;
    let guestUserService: any;
    let guestUserServiceSpy: any;

    beforeEach(async(() => {
        guestUserService = jasmine.createSpyObj('GuestUserService', ['login']);

        TestBed.configureTestingModule({
            declarations: [LoginComponent, ErrorComponent, RegistrationComponent],
            imports: [
                ReactiveFormsModule,
                FormsModule,
                RouterTestingModule,
                HttpClientModule,
                AppRoutingModule,
            ],
            providers: [
                { provide: HTTP_INTERCEPTORS, useClass: JwtInterceptor, multi: true },
                { provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true },
                { provide: APP_BASE_HREF, useValue: '/' },
                { provide: GuestUserService, useValue: guestUserService }]
        })
            .compileComponents();
    }));

    beforeEach(() => {
        fixture = TestBed.createComponent(LoginComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
    });

    it('should create', () => {
        expect(component).toBeTruthy();
    });

  it('should Successfully Submit Registration Form', async(inject([Router], (router) => {
        guestUserServiceSpy = guestUserService.login.and.returnValue(of(new HttpResponse({ status: 200, body: { result: { token: 'DummyTokenIsSent' } } })));

        spyOn(router, 'navigate');
        spyOn(component, 'submitLoginForm').and.callThrough();

        component.loginForm.controls['username'].setValue('hasnani@vishal.com');
        component.loginForm.controls['password'].setValue('12345678');

        component.submitLoginForm();

        expect(component.submitLoginForm).toHaveBeenCalled();
        expect(component.loginForm.invalid).toBe(false);

        expect(guestUserService).toBeDefined();
        expect(guestUserServiceSpy).toBeDefined();
        expect(guestUserServiceSpy).toHaveBeenCalledTimes(1);
        expect(router.navigate).toHaveBeenCalled();
        expect(router.navigate).toHaveBeenCalledWith(['/dashboard']);
    })
    ));

The value of result while running the test case: 运行测试用例时的结果值:

在此输入图像描述

I found that the error is coming as the code is not going through this part "if (result['token'])" But how to access or send body part of the http response form unit test case without effecting the component part. 我发现错误即将发生,因为代码没有通过这部分“if(result ['token'])”但是如何访问或发送http响应的正文部分单元测试用例而不影响组件部分。

use HttpClientTestingModule as import and mock your http response: 使用HttpClientTestingModule作为导入并模拟您的http响应:

httpMock = injector.get(HttpTestingController);
const req = httpMock.expectOne(`path`);
expect(req.request.method).toBe("GET");
req.flush({fakeresponse:true);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM