how do I mock out http post in Angular without using TestBed?

前端 未结 3 1878
一向
一向 2021-01-17 05:25

How do I unit test this login function, specifically the http post part? The http mock I made is not coded correctly to get into the \'if...else\' section of the code. I d

3条回答
  •  醉梦人生
    2021-01-17 05:32

    This is the answer that I ended up using. I was using TestBed in a way that was slow when I could have been using TestBed like the code below:

    import { TestBed, inject} from '@angular/core/testing';
    import { HttpModule,  XHRBackend, Response, ResponseOptions } from '@angular/http';
    import { AuthenticationService } from '../_services/authentication.service';
    import { MockBackend } from '@angular/http/testing';
    
    describe('AuthenticationService', () => {
      let mockbackend, service;
    
      beforeEach(() => {
        localStorage.clear();
        TestBed.configureTestingModule({
          imports: [ HttpModule ],
          providers: [
            AuthenticationService,
            { provide: XHRBackend, useClass: MockBackend }
          ]
        });
      });
    
      beforeEach(inject([AuthenticationService, XHRBackend], (_service, 
    _mockbackend) => {
        service = _service;
        mockbackend = _mockbackend;
      }));
    
      it('should set access token in local storage for successful login', () => 
     {
        const access_token = 'blah83balc380';
        const username = 'test';
        const currentUserExpected = JSON.stringify({ username: username, token: access_token });
        const response = {access_token: access_token};
        const responseOptions = new ResponseOptions();
        responseOptions.body = JSON.stringify(response);
        mockbackend.connections.subscribe(connection => {
          connection.mockRespond(new Response(responseOptions));
        });
        service.login(username, 'test').subscribe(respond => {
          expect(respond).toEqual(true);
          const currentUser = localStorage.getItem('currentUser');
          expect(currentUserExpected).toEqual(currentUser);
        });
      });
    
    it('should not set access token in local storage for unsuccessful login', () =>     {
        const username = 'test';
        const responseOptions = new ResponseOptions();
        responseOptions.body = '';
        responseOptions.status = 401;
        const response = new Response(responseOptions);
        response.ok = false;
        response.statusText = 'Unauthorized';
        response.type = 2;
    
        mockbackend.connections.subscribe(connection => {
          connection.mockRespond(response);
        });
        service.login(username, 'test').subscribe(respond => {
          expect(respond).toEqual(false);
        }, err => {
          const currentUser = localStorage.getItem('currentUser');
          expect(currentUser).toEqual(null);
        });
      });
    });
    

提交回复
热议问题