【问题标题】:Error: No provider for HttpService! In Karma test错误:没有 HttpService 的提供者!在业力测试中
【发布时间】:2017-02-26 10:50:16
【问题描述】:

我有一个 angular 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();
            })));
});

感谢您的帮助:)

【问题讨论】:

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


    【解决方案1】:

    您的语法接缝有误,请检查docs。像这样的东西应该可以工作:

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

    【讨论】:

    • 首先感谢您的快速解答,但错误仍然相同。还有其他想法吗?
    • @Bono 您仍然需要将HttpServiceFront 添加到提供者列表中
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-23
    • 1970-01-01
    • 2018-07-05
    • 2020-11-14
    • 2018-04-24
    • 2017-02-21
    相关资源
    最近更新 更多