Angular2测试http服务不支持地图功能

时间:2016-07-21 20:16:31

标签: testing angular rxjs

我试图针对一个简单的服务创建一个测试,但是我收到的错误是" TypeError:Object不支持属性或方法' map'"当我真正运行这项服务(而不是测试)时它工作正常,我没有任何问题。这是我第一次尝试为Angular2进行测试设置,所以我可能会遗漏一些东西。这是我的组件。

recentActivity.service.ts

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';

import { Observable } from 'rxjs/Observable';
import * as toPromise from 'rxjs/add/operator/toPromise';
import * as map from 'rxjs/add/operator/map';

import { RecentActivity } from './recentActivity.model';

@Injectable()
export class RecentActivityService {

    private baseUrl = '/RecentActivity/';

    constructor(private http: Http) {

    }

    get(): Observable<any> {
        //return undefined;
        return this.http
            .get(this.baseUrl + 'Get')
            .map((response: Response) => response.json())
            //.toPromise()
            ;
    }

}

recentActivity.spec.ts

import { async, describe, it, expect, inject, beforeEach, beforeEachProviders } from '@angular/core/testing';
import { Http, BaseRequestOptions, Response, ResponseOptions } from '@angular/http';
import { MockBackend, MockConnection } from '@angular/http/testing';

import { RecentActivity } from './recentActivity.model';
import { RecentActivityService } from './recentActivity.service';

describe('Recent Activity Service', () => {
    let service: RecentActivityService;
    let mockBackend: MockBackend;
    const mockResponseData: RecentActivity[] = [
        { Name: 'Test Result 1', Url: '#/TestResult1' },
        { Name: 'Test Result 2', Url: '#/TestResult2' },
        { Name: 'Test Result 3', Url: '#/TestResult3' }
    ];

    beforeEachProviders(() => [
        RecentActivityService,
        MockBackend,
        BaseRequestOptions,
        {
            provide: Http,
            useFactory: (backend, options) => new Http(backend, options),
            deps: [MockBackend, BaseRequestOptions]
        }
    ]);

    beforeEach(inject([RecentActivityService, MockBackend], (ras, mb) => {
        service = ras;
        mockBackend = mb;
    }));

    it('Can load list of recent activities', (done) => {
        mockBackend.connections.subscribe((connection: MockConnection) => {
            const responseOpts = new ResponseOptions({ body: JSON.stringify(mockResponseData) });
            connection.mockRespond(new Response(responseOpts));
        });

        service.get()
            .subscribe((results: RecentActivity[]) => {
                expect(results.length).toEqual(3);
                expect(results[0].Name).toEqual('Test Result 1');
                expect(results[1].Name).toEqual('Test Result 2');
                expect(results[2].Name).toEqual('Test Result 3');
                done();
            });
    });
});

单元tests.html

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="content-type" content="text/html;charset=utf-8">
    <title>Unit Tests</title>
    <link rel="stylesheet" href="./libs/jasmine-core/lib/jasmine-core/jasmine.css">

    <script src="./libs/jasmine-core/lib/jasmine-core/jasmine.js"></script>
    <script src="./libs/jasmine-core/lib/jasmine-core/jasmine-html.js"></script>
    <script src="./libs/jasmine-core/lib/jasmine-core/boot.js"></script>

    <script src="./libs/core-js/client/shim.min.js"></script>
    <script src="./libs/zone.js/dist/zone.js"></script>
    <script src="./libs/reflect-metadata/Reflect.js"></script>
    <script src="./libs/systemjs/dist/system.src.js"></script>
    <script src="./libs/rxjs/bundles/Rx.js"></script>

    <script src="~/lib/jquery/dist/jquery.js"></script>
    <script src="~/lib/underscore/underscore.js"></script>
    <script src="~/lib/moment/moment.js"></script>
    <script src="~/lib/bootstrap/dist/js/bootstrap.js"></script>

    <script src="./systemjs.config.js"></script>
    <script>
        // #2. Configure systemjs to use the .js extension
        //     for imports from the app folder
        System.config({
            packages: {
                'app': { defaultExtension: 'js' }
            }
        });

        // #3. Import the spec file explicitly
        Promise.all([
            System.import('app/recentActivity/recentActivity.spec'),
            System.import('app/pipes/styleVisibility.spec')
        ])

      // #4. wait for all imports to load ...
      //     then re-execute `window.onload` which
      //     triggers the Jasmine test-runner start
      //     or explain what went wrong.
      .then(window.onload)
      .catch(console.error.bind(console));
    </script>
</head>
<body>
</body>
</html>

我试图把这些碎片拼凑起来让它起作用,但我无法弄清楚我错过了什么。另外作为旁注我使用Visual Studio 2015,并且还发出警告说&#34;属性地图不存在于类型&#39; Observable&#39;&#34;。

就像我提到的,当我真正运行这项服务时,一切正常,它从我的后端返回我的信息没问题。

2 个答案:

答案 0 :(得分:1)

我所要做的就是将recentActivity.service.ts文件中的导入更改为

从'rxjs / Observable'导入{Observable}; import'rxjs / add / operator / map';

我仍然得到一个错误(红色波浪形)在Visual Studio中,所以如果有人能告诉我如何摆脱它我会很感激。

答案 1 :(得分:0)

以上解决方案也适用于我。但由于我也使用.do和.catch,我也必须导入它们:

import'rxjs / add / operator.do; import'rxjs / add / operator.catch;

希望这也有助于其他人。