繁体   English   中英

在Angle2单元测试中将ReadableStream作为主体嘲讽HTTP后端

[英]Getting ReadableStream as body mocking http backend in angular2 unit test

我想使用本教程模拟http后端。

到目前为止,这是我得到的:

那是测试

describe('DataService', () => {

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        HttpModule
      ],
      providers: [
        MockBackend,
        BaseRequestOptions,
        {
          provide: Http,
          useFactory: (backend: MockBackend, options: BaseRequestOptions) => {
            return new Http(backend, options);
          },
          deps: [MockBackend, BaseRequestOptions]
        },
        DataService,
      ]
    }).compileComponents();
  }));    

  it('should authorize the app', async(inject([DataService, MockBackend],
    (service: DataService, mockBackend: MockBackend) => {
      mockBackend.connections.subscribe((connection) => {
        connection.mockRespond(new Response(new ResponseOptions({
          body: JSON.stringify({ token: '1234-asdf-4321' })
        })));
      });
      service.authorizeApp('1234').subscribe(
        (res) => {
          expect(res.token).toEqual('1234-asdf-4321', res);
        }
      );
    })));
});

这是DataService

export class DataService {

  public constructor(private store: Store<any>, private http: Http) {
    // Live System & Mock server
    this.endPoint = environment.serviceEndPoint 
  }

  authorizeApp(userId): Observable<any> {
    return this.http.post(this.endPoint + AUTH, {
      'username': userId,
      'password': 'pass',
      'uid': true
    }).map(this.extractData)
      .catch(this.handleError);
  }

  extractData(res: Response) {
    const body = res.json();

    return body.data || body || {};
  }

  handleError(error: Response | any): Observable<any> {
    const objError = {
      status: error.status,
      title: ErrorConstant.ERROR_UNKNOWN.TITLE,
      text: ErrorConstant.ERROR_UNKNOWN.TEXT
    };

    console.debug(error._body);

    console.debug(error);
    // Call actions
    switch (error.status) {
      case 401: 
        objError.title = ErrorConstant.ERROR_401.TITLE;
        objError.text = ErrorConstant.ERROR_401.TEXT;
        break;
      case 404:
        objError.title = ErrorConstant.ERROR_404.TITLE;
        objError.text = ErrorConstant.ERROR_404.TEXT;
        break;
    }

    // Return
    return Observable.throw(objError);
  }

我收到此错误:

Chrome 57.0.2987 (Windows 10 0.0.0) DataService should authorize the app FAILED
        Expected undefined to equal '1234-asdf-4321', [object Promise].
            at SafeSubscriber._next (webpack:///src/service/data/data.service.spec.ts:122:28 <- src/test.ts:85196:31) [ProxyZone]
            at SafeSubscriber.__tryOrSetError (webpack:///~/rxjs/Subscriber.js:243:0 <- src/test.ts:7378:16) [ProxyZone]
            at SafeSubscriber.next (webpack:///~/rxjs/Subscriber.js:185:0 <- src/test.ts:7320:27) [ProxyZone]
            at Subscriber._next (webpack:///~/rxjs/Subscriber.js:125:0 <- src/test.ts:7260:26) [ProxyZone]
            at Subscriber.next (webpack:///~/rxjs/Subscriber.js:89:0 <- src/test.ts:7224:18) [ProxyZone]
            at CatchSubscriber.Subscriber._next (webpack:///~/rxjs/Subscriber.js:125:0 <- src/test.ts:7260:26) [ProxyZone]
            at CatchSubscriber.Subscriber.next (webpack:///~/rxjs/Subscriber.js:89:0 <- src/test.ts:7224:18) [ProxyZone]

并且Response对象中的“ body”是ReadableStream而不是JSON字符串。

该问题的解决方案是从“ @ angular / http”导入“ Response”

import { Response } from '@angular/http';

暂无
暂无

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

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