Angular 7: Как получить доступ / отправить только часть тела HTTP-ответа из тестового примера - PullRequest
3 голосов
/ 25 июня 2019

Я создаю модульные тесты в Angular 7 для компонента с асинхронной службой .

вот мой файл компонента:

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

}

блок юнит-теста:

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

Значение результата при выполнении контрольного примера:

enter image description here

Я обнаружил, что ошибка приходит, поскольку код не проходит через эту часть "if (result ['token'])" Но как получить доступ или отправить часть тела модульного тестового примера формы ответа http, не затрагивая компонентную часть.

1 Ответ

1 голос
/ 25 июня 2019

используйте HttpClientTestingModule в качестве импорта и высмеивайте ваш ответ http:

httpMock = injector.get(HttpTestingController);
const req = httpMock.expectOne(`path`);
expect(req.request.method).toBe("GET");
req.flush({fakeresponse:true);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...