поддельная служба, возвращающаяся как неопределенная - PullRequest
0 голосов
/ 22 мая 2018

Я новичок в угловом тестировании.Я пытаюсь научиться макетировать какой-то http-запрос, и я создал макет для своего сервиса, чтобы при вызове функции из сервиса я мог вернуть фиктивные данные, которые я создал.Я продолжаю получать сообщение об ошибке не могу прочитать результаты свойств неопределенных.Я не пропускаю переменную результатов, поэтому я не знаю, что является причиной этой проблемы.Это последнее ожидание в файле спецификации.

TASK SERVICE

import { Observable } from 'rxjs/Rx';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import {Response} from '@angular/http';
import { Injectable } from '@angular/core';

import Task from '../models/task.model';


import 'rxjs/add/operator/map';
import { TaskStatus } from '../models/task-status.model';

@Injectable()
export class TaskService {

  api_url = 'http://localhost:8080';
  taskUrl = `${this.api_url}/tasks`;
  results: Task[];
  constructor(
    private http: HttpClient
  ) { }


  createTask(task: Task, id: number): Observable<any>{
    return this.http.post(`${this.taskUrl}`+'/add/users/' + `${id}`, task);
  }

  getTasks(): Observable<Task[]>{
    return this.http.get(this.taskUrl)
    .map(res  => {
      this.results = res as Task[]
      return res as Task[];
    })
  }

  getTasksNotCompleted():Observable<Task[]>{
    let notcompletedUrl = `${this.taskUrl}`+'/notcompleted'
    return this.http.get(notcompletedUrl)
    .map(res  => {
      return res as Task[];
    })
  }

  getTasksNotStarted():Observable<Task[]>{
    let notcompletedUrl = `${this.taskUrl}`+'/notstarted'
    return this.http.get(notcompletedUrl)
    .map(res  => {
      return res as Task[];
    })
  }

  getTasksInProgress():Observable<Task[]>{
    let notcompletedUrl = `${this.taskUrl}`+'/inprogress'
    return this.http.get(notcompletedUrl)
    .map(res  => {
      return res as Task[];
    })
  }

  getTasksCompleted():Observable<Task[]>{
    let notcompletedUrl = `${this.taskUrl}`+'/complete'
    return this.http.get(notcompletedUrl)
    .map(res  => {
      return res as Task[];
    })
  }

  editTask(task:Task, id: number){
    let editUrl = `${this.taskUrl}`+'/update/users/' + `${id}`
    return this.http.put(editUrl, task);
  }

  deleteTask(id:number):any{
    let deleteUrl = `${this.taskUrl}/${id}`
    return this.http.delete(deleteUrl)
    .map(res  => {
      return res;
    })
  }

  private handleError(error: any): Promise<any> {
    console.error('An error occurred', error);
    return Promise.reject(error.message || error);
  }

}

TASK.SERVICE SPEC

import { HttpClientModule } from '@angular/common/http';
import { TestBed, inject, getTestBed, async, fakeAsync, tick } from '@angular/core/testing';
import {MockBackend, MockConnection} from '@angular/http/testing';
import {ResponseOptions} from '@angular/http';
import {
  Headers, BaseRequestOptions,
  Response, HttpModule, Http, XHRBackend, RequestMethod
} from '@angular/http';

import { TaskService } from './task.service';
import { Task } from '../models/task.model';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { TaskStatus } from '../models/task-status.model';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { User } from '../models/user.model';
import { defer } from 'rxjs/observable/defer';
import {mock, instance, when, verify} from 'ts-mockito';
import { Observable } from 'rxjs/Rx';



describe('TaskService: getTasks', () => {
  let service: TaskService;
  let taskService: TaskService;
  let mockTaskService: TaskService;
  let mockBackend: MockBackend;
  let httpClient: HttpClient;
  let httpTestingController: HttpTestingController;
  let httpClientSpy: { get: jasmine.Spy };

  beforeEach(async(() => {
    //service = new TaskService(new HttpClient());
    httpClientSpy = jasmine.createSpyObj('HttpClient', ['get']);
    service = new TaskService(<any> httpClientSpy);
    mockTaskService = mock(TaskService);


    TestBed.configureTestingModule({
      imports: [
        HttpClientTestingModule,
      ],
      providers: [
        TaskService, 
        MockBackend,
        BaseRequestOptions,
        {
          provide: HttpClient,
          deps: [MockBackend, BaseRequestOptions],
          useFactory:
            (backend, options) => {
              return new Http(backend, options);
            }
       }
      ]
    });
    httpClient = TestBed.get(HttpClient);
    httpTestingController = TestBed.get(HttpTestingController);
    //mockBackend = getTestBed().get(MockBackend);
    mockBackend = TestBed.get(MockBackend);
    taskService =  TestBed.get(TaskService);
  }));

  afterEach(() => {
    // After every test, assert that there are no more pending requests.
    httpTestingController.verify();
  });

  it('should be created', inject([TaskService], (service: TaskService) => {
    expect(service).toBeTruthy();
  }));


  it('#getObservableValue should return value from observable', 
    () => {
    const expectedTasks: Task[] =
    [{ _id: 1, name: 'A', description:"description", status: TaskStatus.notstarted, assignedUser: new User() }];

  httpClientSpy.get.and.returnValue(asyncData(expectedTasks));

  service.getTasks().subscribe(
    tasks => expect(tasks).toEqual(expectedTasks, 'expected tasks'),
    fail
  );
  expect(httpClientSpy.get.calls.count()).toBe(1, 'one call');
  });

  it('should return tasks', fakeAsync(() => {
    let response = {
    "resultCount":1,
     "results": [{ "_id": 1, "name": 'A', "description":"description", "status": TaskStatus.notstarted, "assignedUser": new User() }]
    };

    mockBackend.connections.subscribe( connection => {
      connection.mockRespond(new Response(<ResponseOptions>{
        body: JSON.stringify(response)
    }));
  });

    taskService.getTasks();
    tick();


  }))

  expect(taskService.results.length).toBe(1);


  function asyncData<T>(data: T) {
    return defer(() => Promise.resolve(data));
  }
});

1 Ответ

0 голосов
/ 22 мая 2018

Ваша проблема в неправильном коде.

// all the other code of TASK.SERVICE SPEC
...

// the last correct it-condition
it('should return tasks', fakeAsync(() => {
      let response = {
          "resultCount":1,
          "results": [{ "_id": 1, "name": 'A', "description":"description", 
            "status": TaskStatus.notstarted, "assignedUser": new User() }]
      };

      mockBackend.connections.subscribe( connection => {
         connection.mockRespond(new Response(<ResponseOptions>{
         body: JSON.stringify(response)
      }));
});

// <<< 
// Your problem starts here. the following code is outside any it-condition
// and thus the last expect() is always undefined. Wrap an it-condition around
// this block of code and you'll see your mock running.
// >>>  

taskService.getTasks();
      tick();
   }))

   expect(taskService.results.length).toBe(1);


  function asyncData<T>(data: T) {
    return defer(() => Promise.resolve(data));
  }
...