Angular 2 Observable Service Karma Jasmine 单元测试不起作用 [英] Angular 2 Observable Service Karma Jasmine Unit Test not working

查看:18
本文介绍了Angular 2 Observable Service Karma Jasmine 单元测试不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Angular 2 和 Karma + Jasmine 单元测试的新手.我无法弄清楚我为了让这个单元测试使用模拟响应而犯了什么语义错误.在控制台中,当expect(items[0].itemId).toBe(2);"运行时,它说 items[0].itemId 未定义.

I am a newbie to Angular 2 and Karma + Jasmine unit tests. I cannot figure out what semantic error I have made in order to make this unit test use the mocked response. In the console, when "expect(items[0].itemId).toBe(2);" is run, it says items[0].itemId is undefined.

有人可以帮助我或为我指明正确的方向吗?如果您需要任何其他信息,请告诉我.谢谢!

Would someone be able to help me out or point me in the right direction? Please let me know if you need any additional information. Thanks!

item.ts

export class Item {
     itemId: number;
     itemName: string;
     itemDescription: string;
}

item.service.ts

item.service.ts

import { Injectable, Inject } from '@angular/core';
    import { Headers, Http } from '@angular/http';
    import { Observable } from 'rxjs/Rx';
    import { Item } from './item';
@Injectable()
export class ItemService {
    private headers = new Headers({'Content-Type': 'application/json'});

    constructor(
    private http: Http)
    {

    }

    getItems(listOptions: Object): Observable<Item[]> {
    return this.http.post('/listItems', listOptions, {headers:this.headers})
       .map(response => response.json() as Item[])
  }
}

item.service.spec.ts

item.service.spec.ts

import { TestBed, fakeAsync, inject, tick } from '@angular/core/testing';
import { MockBackend } from '@angular/http/testing';
import { Http, BaseRequestOptions, Response, ResponseOptions } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import { ItemService } from './item.service';
import { Item } from './item';


describe('ItemService', () => {
  let mockResponse, matchingItem, connection;

  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [
        ItemService,
        MockBackend,
        BaseRequestOptions,
        {
          provide: Http,
          useFactory: (backend, defaultOptions) => new Http(backend, defaultOptions),
          deps: [MockBackend, BaseRequestOptions]
        },
        // { provide: XHRBackend, useClass: MockBackend }        
      ]
    });

    const items = [
      {
        "itemId":2,
        "itemName":"test item1",
        "itemDescription":"hello hello"        
      },
      {
        "itemId":1,
        "itemName":"name2124111121",
        "itemDescription":"description212412112"        
      }
    ];
    mockResponse = new Response(new ResponseOptions({body: {data: items}, status: 200}));
  });

  describe('getItems', () => {

    //Subscribing to the connection and storing it for later
    it('should return all the items',inject([ItemService, MockBackend], (service: ItemService, backend: MockBackend) => {

        backend.connections.subscribe(connection => {
          connection.mockRespond(mockResponse);
        });
        service.getItems({isActive: true, sortColumn: "lastModifiedDateUtc", sortOrder: "desc"})
        .subscribe((items: Item[]) => {
          expect(items.length).toBe(2);
        });
      }));
    });
  });

Plunkr:https://plnkr.co/edit/m7In2eVh6oXu8VNYFf9l?p=preview(Plunkr 有一些错误,我也需要帮助,但主要文件在那里)

Plunkr: https://plnkr.co/edit/m7In2eVh6oXu8VNYFf9l?p=preview (There are some errors with the Plunkr I need help with as well but the main files are there)

推荐答案

模拟响应正文与实际响应正文不匹配,这就是我收到错误的原因.

The mockResponse body did not match the actual response body, that is why I was getting the error.

mockResponse = new Response(new ResponseOptions({body: {data: items}, status: 200})); 应该是 mockResponse = new Response(new ResponseOptions({body:项目,状态:200}));

这篇关于Angular 2 Observable Service Karma Jasmine 单元测试不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆