错误:没有HttpService的提供者!在Karma测试中

时间:2016-10-17 12:40:25

标签: http angular error-handling mocking karma-jasmine

我有一个角度2工具来监控服务器,刚开始测试。当我尝试模拟httpService时,我不知道如何模拟Rest-API,所以我在线查看,修复了一些错误,现在我就陷入了这个错误。
这里错误:

Chrome 53.0.2785 (Windows 10 0.0.0) HttpServiceFront should use an HTTP call Servers FAILED
        Error: No provider for HttpServiceFront!
            at NoProviderError.Error (native)
            ...
            at drainMicroTaskQueue (webpack:///~/zone.js/dist/zone.js:368:0 <- config/karma-test-shim.js:6854:36)
Chrome 53.0.2785 (Windows 10 0.0.0): Executed 2 of 3 (1 FAILED) (skipped 1) (0.268 secs / 0.057 secs)

这是我的测试用例:

import {
    ResponseOptions,
    Response,
    Http,
    BaseRequestOptions,
    RequestMethod
} from '@angular/http';

import {
    TestBed, fakeAsync, inject
} from '@angular/core/testing';

import { HttpServiceFront } from '../app/services/httpServiceFront';

import { MockBackend, MockConnection } from '@angular/http/testing';

const mockHttpProvider = {
    deps: [ MockBackend, BaseRequestOptions ],
    useFactory: (backend: MockBackend, defaultOptions: BaseRequestOptions) => {
        return new Http(backend, defaultOptions);
    }
};

describe('HttpServiceFront', () => {
    beforeEach(() => {
        {Http, mockHttpProvider}
        TestBed.configureTestingModule(
            [MockBackend,
            BaseRequestOptions]
        )
    });

    it('should use an HTTP call Servers',
        inject(
            [HttpServiceFront, MockBackend],
            fakeAsync((service: HttpServiceFront, backend: MockBackend) => {
                backend.connections.subscribe((connection: MockConnection) => {

                    expect(connection.request.method).toBe(RequestMethod.Get);
                    expect(connection.request.url).toBe(
                        'http://localhost:8080/server');
                });

                service.getServers();
            })));
});

感谢您的帮助:)

1 个答案:

答案 0 :(得分:7)

您的语法错误,请检查docs。这样的事情应该有效:

beforeEach(() => {
    TestBed.configureTestingModule({
        providers: [
          { provide: Http, useValue: mockHttpProvider },
          MockBackend,
          BaseRequestOptions]
    })
});