测试HTTPClient Angular 4“;“预期未定义待定义”;

测试HTTPClient Angular 4“;“预期未定义待定义”;,angular,integration-testing,karma-jasmine,Angular,Integration Testing,Karma Jasmine,测试Angular 4 HTTPClient 此后 在职 getBlogs(){ return this._http.get(this.blogsURL+'blogs') .map((result: Response ) => { this.blogs = result['blogs']; return this.blogs; }) } 然后测试: 我开始将服务和HttpTestin

测试Angular 4 HTTPClient

此后

在职

 getBlogs(){
     return this._http.get(this.blogsURL+'blogs')
          .map((result: Response ) => {
               this.blogs  = result['blogs'];
               return this.blogs;
     })
 }
然后测试: 我开始将服务和HttpTestingController注入到it块中,但在每项工作正常之前将其放入

当调用request.flush并激发subscribe方法时,就会出现问题,因为没有返回结果

import { TestBed, inject } from '@angular/core/testing';
import { HttpClientModule } from '@angular/common/http';
import {HttpClientTestingModule, HttpTestingController} from '@angular/common/http/testing';

import { BlogsService } from './blogs.service';
import { Blog } from '../models/blog';


describe('BlogsService', () => {
  let service:BlogsService;
  let blogsURL:string;
  let httpMock:HttpTestingController;
  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [BlogsService],
      imports: [HttpClientTestingModule]
    });
    service = TestBed.get(BlogsService);
    httpMock = TestBed.get(HttpTestingController);
    blogsURL = 'http://localhost:3000/'
  });



 it('#getBlogs should return data',() => {
   service
       .getBlogs()
       .subscribe(result => {
         expect(result).toBeDefined();
         expect(result.length).toBe(2);
         expect(result).toEqual([
          {
            id: 1,
            name: 'Foo',
            numSales: 100
          }, {
            id: 2,
            name: 'Bar',
            numSales: 200
          }
        ]);
       });


     // look up our request and access it
     const request = httpMock.expectOne(blogsURL+'blogs');
     // verify it is a GET
     expect(request.request.method).toEqual('GET');

     // Now, provide the answer to the caller above,
     // flushing the data down the pipe to the caller and
     // triggering the test's subscribe method
     request.flush([
          {
            id: 1,
            name: 'Foo',
            numSales: 100
          }, {
            id: 2,
            name: 'Bar',
            numSales: 200
          }
        ]);
     //
    //  // make sure it actually got processed...
     httpMock.verify();
   });


});

假设您的url正确返回了数据,您似乎忘记了服务中的
map
函数中的
result.json()。Angular http服务返回一个对象
响应
,您需要调用它的
json
函数来获取实际的json对象,然后才能返回数据。将您的
getBlogs
方法更改为以下内容

 getBlogs(){
     return this._http.get(this.blogsURL+'blogs')
      .map((result: Response ) => {
           const resp = result.json();
           this.blogs  = resp['blogs'];
           return this.blogs;
      })
 }
有一些尝试和错误(主要是错误)

我已经解决了这个问题,我想我对测试HTTPClient有了更好的理解

让我们从数据库服务器返回的内容开始

{message: 'Success', blogs: blogs}
一个json对象,包含一条消息和一组名为blogs的blog

接下来是服务中名为getBlogs的函数

这两条重要路线是:

  this.blogs  = res['blogs'];
  return this.blogs;
这样做的目的是从结果中提取blogs数组,将其添加到变量this.blogs中,然后返回它

我一直忘记的是,我正在测试服务中的实际功能,而不是单独的实体,因此测试需要博客 要返回,这就是我得到未定义错误的原因,因此我添加了一个模拟博客数组:

  blogs = [{_id: '1234',title: 'title1-test', vidUrl: 'XpiipWULkXk', script:'Some test script'}, {_id: '12345',title: 'title2', vidUrl: 'XpiipWULkXk', script:'Some test script2'}];
然后在flush语句中

request.flush({message:"Success", blogs:blogs});
因为这需要模拟从服务器返回的内容,所以代码可以提取它

完整代码:

import { TestBed, inject } from '@angular/core/testing';
import { HttpClientModule } from '@angular/common/http';
import {HttpClientTestingModule, HttpTestingController} from '@angular/common/http/testing';

import { BlogsService } from './blogs.service';
import { Blog } from '../models/blog';


describe('BlogsService', () => {
  let service:BlogsService;
  let blogsURL:string;
  let httpMock: HttpTestingController;
  let blogs:Blog[];

  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [BlogsService],
      imports: [HttpClientTestingModule]
    });
    service = TestBed.get(BlogsService);
    httpMock = TestBed.get(HttpTestingController);
    blogsURL = 'http://localhost:3000/';
    blogs = [{_id: '1234',title: 'title1-test', vidUrl: 'XpiipWULkXk', script:'Some test script'}, {_id: '12345',title: 'title2', vidUrl: 'XpiipWULkXk', script:'Some test script2'}];

  });


  it('#getBlogs should return data',() => {
    service
        .getBlogs()
        .subscribe(results => {
          expect(results).toBeDefined();
          //has to be what is returned by the function
          expect(results).toEqual(blogs);
          console.log(results)

        });
      // look up our request and access it
      const request = httpMock.expectOne(blogsURL+'blogs');
      // verify it is a GET
      expect(request.request.method).toEqual('GET');

      request.flush({message:"Success", blogs:blogs});
     //  // make sure it actually got processed...
      httpMock.verify();
    });


});

感谢您的回复,但是我使用的是HTTPClient Angular 4,当我看到您的
时,它不需要做得很好。