【问题标题】:Testing Service : Difference between MockBackend method and spyOn().and.returnValue() method测试服务:MockBackend 方法和 spyOn().and.returnValue() 方法的区别
【发布时间】:2017-09-07 23:50:23
【问题描述】:

这两个测试似乎有效(至少在我的情况下)

这两种方法之间是否存在一些特定差异? 以及如何决定我应该使用哪个(使用 Http 测试服务的最佳实践)?

1.使用 MockBackend 方法

beforeEach(() => {
  TestBed.configureTestingModule({
    providers: [
      MyService,
      MockBackend,
      BaseRequestOptions,
      {
          provide: Http,
          deps: [MockBackend, BaseRequestOptions],
          useFactory: (backend: XHRBackend, defaultOptions: BaseRequestOptions) => new Http(backend, defaultOptions)
      }
    ],
    imports: [HttpModule]
  }).compileComponents();
});

it('#getResources should get an items list', 
  async(inject([MyService], (service: MyService) => {

    TestBed.get(MockBackend).connections.subscribe(
        (connection: MockConnection) => connection.mockRespond(new Response(
          new ResponseOptions({
            body: {
              items: ['foo','bar']
            }
          })
        ))
    );

    service.getResources('/foobar').subscribe(items => {
        expect(items).toEqual(['foo','bar']);
    });

  }))
);

2。使用 spyOn().and.returnValue() 方法

let backend: XHRBackend;
let defaultOptions: BaseRequestOptions;
let http = new Http(backend, defaultOptions);

it('#getResources should get an items list', async(() => {

  const spy = spyOn(http, 'get')
              .and.returnValue(
                Observable.of(new Response(new ResponseOptions({
                    body: {items: ['foo','bar']}
                }))
              ));

  let service = new MyService(http);
  service.getResources('/foobar').subscribe(items => {
    expect(items).toEqual(['foo','bar']);
  });

}));

【问题讨论】:

    标签: unit-testing angular http-mock


    【解决方案1】:

    使用MockBackend,因为您可能还应该测试其他内容,例如 URL 是否正确、添加了正确的标头等。所有这些都可以从 Request 获得987654324@

    TestBed.get(MockBackend).connections
     .subscribe((connection: MockConnection) => {
       const request = connection.request;
       expect(request.url).toBe(...)
     })
    );
    

    这些是您应该测试的内容,因为具有意外的 URL 会导致应用程序中的请求失败。所以你应该测试一下。以及标头,以及与请求相关的任何其他内容。

    【讨论】:

    • 说得通;)谢谢。
    猜你喜欢
    • 2018-04-10
    • 1970-01-01
    • 1970-01-01
    • 2019-05-15
    • 1970-01-01
    • 2018-11-22
    • 2018-02-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多