网络科技

    今日:1164| 主题:245866
收藏本版
互联网、科技极客的综合动态。

[其他] Testing Services with Http in Angular 2

[复制链接]
奇葩朵朵向阳开 发表于 2016-11-29 02:46:26
11 3

立即注册CoLaBug.com会员,免费获得投稿人的专业资料,享用更多功能,玩转个人品牌!

您需要 登录 才可以下载或查看,没有帐号?立即注册

x
Testing is important. That’s why Angular comes with a testing story out-of-the-box. Due to its dependency injection system, it’s fairly easy to mock dependencies, swap out Angular modules, or even create so called “shallow” tests, which enable us to test Angular components, without actually depending on their views (DOM). In this article we’re going to take a look at how to unit test a service that performs http calls, since there’s a little bit more knowledge required to make this work.
      TABLE OF CONTENTS

   
          
  • The Service we want to test      
  • Configuring a testing module
               
    • Overriding the Http Backend        
                

    •          
    • Mocking http responses         
    • Making the test asynchronous        
             
    The Service we want to test

  Let’s start off by taking a look at the service want to test. Sure, sometimes we actually want to do test-driven development, where we    firstcreate the test and    thenimplement the actual service. However, from a learning point of view, it’s probably easier to grasp testing concepts when we first explore the APIs we want to test.  
  At thoughtram, we’re currently recording screencasts and video tutorials, to provide additional content to our blog readers. In order to make all these videos more explorable, we’re also building a little application that lets users browse and watch them. The video data is hosted on Vimeo, so we’ve created a service that fetches the data from their API.
  Here’s what our    VideoServiceroughly looks like:  
     
  1. import { Injectable, Inject } from [email protected]/core';
  2. import { VIMEO_API_URL } from '../config';
  3. import 'rxjs/add/operator/map';
  4. @Injectable()
  5. export class VideoService {
  6.   constructor(private http: Http, @Inject(VIMEO_API_URL) private apiUrl) {}
  7.   getVideos() {
  8.     return this.http.get(`${this.apiUrl}/videos`)
  9.                     .map(res => res.json().data);
  10.   }
  11. }
复制代码
       getVideos()returns an    Observable<Array<Video>>. This is just an excerpt of the actual service we use in production. In reality, we cache the responses so we don’t peform an http request every single time we call this method.  
  Special Tip: If the    @Inject()decorator is new to you, make sure to checkout thisarticle  
  To use this service in our application, we first need to create a provider for it on our application module, later we will use it in our tests:
     
  1. @NgModule({
  2.   imports: [HttpModule]
  3.   providers: [VideoService]
  4.   ...
  5. })
  6. export class AppModule {}
复制代码
   Since the API returns an Observable, we need to subscribe to it to actually perform the http request. That’s why the call side of the method looks something like this:
     
  1. @Component()
  2. export class VideoDashboard {
  3.   
  4.   private videos = [];
  5.   constructor(private videoService: VideoService) {}
  6.   ngOnInit() {
  7.     this.videoService.getVideos()
  8.         .subscribe(videos => this.videos = videos);
  9.   }
  10. }
复制代码
   Notice how we’re passing a callback function to access the video data that is emitted by the Observable. We need to keep that in mind when testing these methods, because we can’t call them synchronously. To get an introduction to Observables in conjunction with Angular, make sure to readthis article.  
  Alright, now that we know what the service we want to test looks like, let’s take a look at writing the tests.
  Configuring a testing module

  Before we can start writing test specs for our service APIs, we need to configure a testing module. This is needed because in our tests, we want to make sure that we aren’t performing actual http requests and use a    MockBackendinstead. Our goal is to isolate the test scenario as much as we can without touching any other    realdependencies. Since NgModules configure injectors, a testing module allows us to do exactly that.  
  When testing services or components that don’t have any dependencies, we can just go ahead an instantiate them manually, using their constructors like this:
     
  1. it('should do something', () => {
  2.   let service = new VimeoService();
  3.   expect(service.foo).toEqual('bar');
  4. });
复制代码
   Special Tip: When testing components and services that don’t have any dependencies, we don’t necessarily need to create a testing module.  
  To configure a testing module, we use Angular’s    TestBed.    TestBedis Angular’s primary API to configure and initialize environments for unit testing and provides methods for creating components and services in unit tests. We can create a module that overrides the actual dependencies with testing dependencies, using    TestBed.configureTestingModule().  
     
  1. import { TestBed } from [email protected]/core/testing';
  2. describe('VideoService', () => {
  3.   beforeEach(() => {
  4.     TestBed.configureTestingModule({
  5.       ...
  6.     });
  7.   });
  8. });
复制代码
   This will create an NgModule for every test spec, as we’re running this code as part of a    beforeEach()block. This is a    JasmineAPI. If you aren’t familiar with Jasmine, we highly recommend reading their documentation.  
  Okay, but what does a configuration for such a testing module look like? Well, it’s an NgModule, so it has pretty much the same API. Let’s start with adding an    importfor    HttpModuleand a provider for    VideoServicelike this:  
     
  1. import { HttpModule } from [email protected]/http';
  2. import { VideoService } from './video.service';
  3. import { VIMEO_API_URL } from '../config';
  4. ...
  5. TestBed.configureTestingModule({
  6.   imports: [HttpModule],
  7.   providers: [
  8.     { provide: VIMEO_API_URL, useValue: 'http://example.com' },
  9.     VideoService
  10.   ]
  11. });
  12. ...
复制代码
   This configures an injector for our tests that knows how to create our    VideoService, as well as the    Httpservice. However, what we actually want is an    Httpservice that doesn’t really perform http requests. How do we do that? It turns out that the    Httpservice uses a    ConnectionBackendto perform requests. If we find a way to swap that one out with a different backend, we get what we want.  
  To give a better picture, here’s what the constructor of Angular’s    Httpservice looks like:  
     
  1. @Injectable()
  2. export class Http {
  3.   constructor(
  4.     protected _backend: ConnectionBackend,
  5.     protected _defaultOptions: RequestOptions
  6.   ) {}
  7.   ...
  8. }
复制代码
   By adding an    HttpModuleto our testing module, providers for    Http,    ConnectionBackendand    RequestOptionsare already configured. However, using an NgModule’s    providersproperty, we can    overrideproviders that have been introduced by other imported NgModules! This is where Angular’s dependency injection really shines!  
  Overriding the Http Backend

  In practice, this means we need to create a new provider for    Http, which instantiates the class with a different    ConnectionBackend. Angular’s http module comes with a testing class    MockBackend.    Thatone not only ensures that no real http requests are performed, it also provides APIs to subscribe to opened connections and send mock responses.  
  With the    useFactorystrategy of a provider configuration, we can then create    Httpinstances that use a different    ConnectionBackend. Here’s what that looks like:  
     
  1. import { HttpModule, Http, BaseRequestOptions } from [email protected]/http';
  2. import { MockBackend } from [email protected]/http/testing';
  3. ...
  4. TestBed.configureTestingModule({
  5.   ...
  6.   providers: [
  7.     ...
  8.     {
  9.       provide: Http,
  10.       useFactory: (mockBackend, options) => {
  11.         return new Http(mockBackend, options);
  12.       },
  13.       deps: [MockBackend, BaseRequestOptions]
  14.     },
  15.     MockBackend,
  16.     BaseRequestOptions
  17.   ]
  18. });
  19. ...
复制代码
   Wow, that’s a lot of code! Let’s go through this step by step:
  
       
  • We create a new provider for      Httpthat uses      useFactorystrategy, so we are in charge of creating the actual service instance.   
  •       Httpasks for a      ConnectionBackendand      RequestOptions. That’s why we pass      mockBackendand      optionsto the constructor.   
  • To make sure Angular knows what we mean by      mockBackendand      options, we add      deps: [MockBackend, BaseRequestOptions]. This is needed because metadata (Type Annotations) in normal functions aren’t preserved at runtime.   
  • We add providers for      MockBackendand      BaseRequestOptions  
  Awesome! We’ve created a testing module that uses an    Httpservice with a    MockBackend. Now let’s take a look at how to actually test our service.  
  Testing the service

  When writing unit tests with Jasmine, every test spec is written as an    it()block, where an assertion is made and then checked if that assertion is true or not. We won’t go into too much detail here, since there’s a lot of documentation for Jasmine out there. We want to test if our    VideoServicereturns an    Observable<Array<Video>>, so let’s start with the following    it()statement:  
     
  1. describe('VideoService', () => {
  2.   ...
  3.   describe('getVideos()', () => {
  4.     it('should return an Observable<Array<Video>>', () => {
  5.       // test goes here
  6.     });
  7.   });
  8. });
复制代码
   We’ve also added another nested    describe()block so we can group all tests that are related to that particular method we test. Okay, next we need to get an instance of our    VideoService. Since we’ve created a testing module that comes with all providers for our services, we can use dependency injection to inject instances accordingly.  
  Injecting Services

  Angular’s testing module comes with a helper function    inject(), which injects service dependencies. This turns out to be super handy as we don’t have to take care of getting access to the injector ourselves.    inject()takes a list of provider tokens and a function with the test code, and it    returnsa function in which the test code is executed. That’s why we can pass it straight to our spec and remove the anonymous function we’ve introduced in the first place:  
     
  1. import { TestBed, inject } from [email protected]/core/testing';
  2. ...
  3. it('should return an Observable<Array<Video>>',
  4.   inject([/* provider tokens */], (/* dependencies */) => {
  5.   // test goes here
  6. }));
复制代码
   Cool, now we have all the tools we need to inject our services and write a test. Let’s go ahead an do exactly that. Once we have our service injected, we can call    getVideos()and subscribe to the Observable it returns, to then test if the emitted value is the one we expect.  
     
  1. @NgModule({
  2.   imports: [HttpModule]
  3.   providers: [VideoService]
  4.   ...
  5. })
  6. export class AppModule {}0
复制代码
   This test is not finished yet.Right now we’re having a test that expects some certain data that is going to be emitted by    getVideos(), however, remember we’ve swapped out the    Httpbackend so there’s no actual http request performed? Right, if there’s no request performed, this Observable won’t emit anything. We need a way to fake a response that is emitted when we subscribe to our Observable.  
  Mocking http responses

  As mentioned earlier,    MockBackendprovides APIs to not only subscribe to http connections, it also enables us to send mock responses. What we want is, when the underlying    Httpservice creates a connection (performs a request), send a fake http response with the data we’re asserting in our    getVideos()subscription.  
  We can subscribe to all opened http connections via    MockBackend.connections, and get access to a    MockConnectionlike this:  
     
  1. @NgModule({
  2.   imports: [HttpModule]
  3.   providers: [VideoService]
  4.   ...
  5. })
  6. export class AppModule {}1
复制代码
   The next thing we need to do, is to make the connection send a response. We use    MockConnection.mockRespond()for that, which takes an instance of Angular’s    Responseclass. In order to define what the response looks like, we need to create    ResponseOptionsand define the response body we want to send (which is a string):  
     
  1. @NgModule({
  2.   imports: [HttpModule]
  3.   providers: [VideoService]
  4.   ...
  5. })
  6. export class AppModule {}2
复制代码
   Cool! With this code we now get a fake response inside that particular test spec. Even though it looks like we’re done,    there’s one more thing we need to do.  
  Making the test asynchronous

  Because the code we want to test is asynchronous, we need to inform Jasmine when the asynchronous operation is done, so it can run our assertions. This is not a problem when testing synchronous code, because the assertions are always executed in the same tick as the code we test. However, when testing asynchronous code, assertions might be executed later in another tick. That’s why we can explicitly tell Jasmine that we’re writing an asynchronous test. We just need to also tell Jasmine, when the actual code is “done”.
  Jasmine usually provides access to a function    done()that we can ask for inside our test spec and then call it when we think our code is done. This looks something like this:  
     
  1. @NgModule({
  2.   imports: [HttpModule]
  3.   providers: [VideoService]
  4.   ...
  5. })
  6. export class AppModule {}3
复制代码
   Angular makes this a little bit more convenient. It comes with another helper function    async()which takes a test spec and then runs    done()behind the scenes for us. This is pretty cool, because we can write our test code as if it was synchronous!  
  How does that work? Well… Angular takes advantage of a feature called Zones. It creates a “testZone”, which automatically figures out when it needs to call    done(). If you havent heard about Zones before, we wrote about themhere andhere.  
  Special Tip: Angular’s    async()function executes test specs in a test zone!  
  Let’s update our test to run inside Angular’s test zone:
     
  1. @NgModule({
  2.   imports: [HttpModule]
  3.   providers: [VideoService]
  4.   ...
  5. })
  6. export class AppModule {}4
复制代码
   Notice that all we did was wrapping the    inject()call in an    async()call.  
  The complete code

  Putting it all together, here’s what the test spec for the    getVideos()method looks like:  
     
  1. @NgModule({
  2.   imports: [HttpModule]
  3.   providers: [VideoService]
  4.   ...
  5. })
  6. export class AppModule {}5
复制代码
   This pattern works for pretty much every test that involves http operations. Hopefully this gave you a better understanding of what    TestBed,    MockBackendand    asyncare all about.
友荐云推荐




上一篇:Google Search Console Changes "Submit To Index" To "Request Indexing"
下一篇:Getting Started with SLIM 3, A PHP Microframework
酷辣虫提示酷辣虫禁止发表任何与中华人民共和国法律有抵触的内容!所有内容由用户发布,并不代表酷辣虫的观点,酷辣虫无法对用户发布内容真实性提供任何的保证,请自行验证并承担风险与后果。如您有版权、违规等问题,请通过"联系我们"或"违规举报"告知我们处理。

yh7jt 发表于 2016-11-29 05:21:45
现在的男人们,白天是非诚勿扰,晚上让子弹飞,结果就有了很多肇事孤儿
回复 支持 反对

使用道具 举报

linfern 发表于 2016-11-29 05:21:46
精华帖的节奏啊!
回复 支持 反对

使用道具 举报

kwrh1945619 发表于 前天 22:33
逆袭成功。。。。。。
回复 支持 反对

使用道具 举报

*滑动验证:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

我要投稿

推荐阅读

扫码访问 @iTTTTT瑞翔 的微博
回页顶回复上一篇下一篇回列表手机版
手机版/CoLaBug.com ( 粤ICP备05003221号 | 文网文[2010]257号 )|网站地图 酷辣虫

© 2001-2016 Comsenz Inc. Design: Dean. DiscuzFans.

返回顶部 返回列表