Angular 2.1无法设置基本提供程序,因为它已被调用(...)

Jim*_*imi 2 typescript angular2-testing angular

我正在尝试测试包含服务的基本角度2组件.当我运行测试时,我遇到以下错误.组件,服务和测试都很小,它们在浏览器中运行良好.我不确定我在测试中缺少什么才能使它工作.

任何帮助表示赞赏.

Uncaught Error: Cannot set base providers because it has already been called(…)

Uncaught Error: Error in ./TestComponent class TestComponent - inline template:0:0 caused by: No provider for Http!
Error: No provider for Http!
    at NoProviderError.BaseError [as constructor] (http://localhost:9876/base/karma-shim.js:4006:34)
    at NoProviderError.AbstractProviderError [as constructor] (http://localhost:9876/base/karma-shim.js:33221:16)
    at new NoProviderError (http://localhost:9876/base/karma-shim.js:33252:16)
    at ReflectiveInjector_._throwOrNull (http://localhost:9876/base/karma-shim.js:57969:19)
    at ReflectiveInjector_._getByKeyDefault (http://localhost:9876/base/karma-shim.js:57997:25)
    at ReflectiveInjector_._getByKey (http://localhost:9876/base/karma-shim.js:57960:25)
    at ReflectiveInjector_.get (http://localhost:9876/base/karma-shim.js:57769:21)
    at TestBed.get (http://localhost:9876/base/karma-shim.js:5778:67)
    at ElementInjector.get (http://localhost:9876/base/karma-shim.js:58133:48)
    at _View_TestComponent0.createInternal (TestComponent.ngfactory.js:21:68)
    at _View_TestComponent0.AppView.create (http://localhost:9876/base/karma-shim.js:58492:21)
    at _View_TestComponent0.DebugAppView.create (http://localhost:9876/base/karma-shim.js:58704:44)
    at _View_TestComponent_Host0.createInternal (TestComponent_Host.ngfactory.js:18:14)
    at _View_TestComponent_Host0.AppView.create (http://localhost:9876/base/karma-shim.js:58492:21)
    at _View_TestComponent_Host0.DebugAppView.create (http://localhost:9876/base/karma-shim.js:58704:44)
    at ComponentFactory.create (http://localhost:9876/base/karma-shim.js:33751:36)
    at initComponent (http://localhost:9876/base/karma-shim.js:5816:53)
    at ZoneDelegate.invoke (http://localhost:9876/base/karma-shim.js:48531:26)
    at ProxyZoneSpec.onInvoke (http://localhost:9876/base/karma-shim.js:48195:39)
    at ZoneDelegate.invoke (http://localhost:9876/base/karma-shim.js:48530:32)
    at Object.onInvoke (http://localhost:9876/base/karma-shim.js:22909:37)
    at ZoneDelegate.invoke (http://localhost:9876/base/karma-shim.js:48530:32)
    at Zone.run (http://localhost:9876/base/karma-shim.js:48413:43)
    at NgZone.run (http://localhost:9876/base/karma-shim.js:22799:62)
    at TestBed.createComponent (http://localhost:9876/base/karma-shim.js:5819:62)
    at Function.TestBed.createComponent (http://localhost:9876/base/karma-shim.js:5634:33)
    at Object.<anonymous> (http://localhost:9876/base/karma-shim.js:63273:41)
    at ZoneDelegate.invoke (http://localhost:9876/base/karma-shim.js:48531:26)
    at ProxyZoneSpec.onInvoke (http://localhost:9876/base/karma-shim.js:48195:39)
    at ZoneDelegate.invoke (http://localhost:9876/base/karma-shim.js:48530:32)
    at Zone.run (http://localhost:9876/base/karma-shim.js:48413:43)
    at Object.<anonymous> (http://localhost:9876/base/karma-shim.js:47910:34)
    at ZoneQueueRunner.jasmine.QueueRunner.ZoneQueueRunner.execute (http://localhost:9876/base/karma-shim.js:47940:42)
    at ZoneQueueRunner.jasmine.QueueRunner.ZoneQueueRunner.execute (http://localhost:9876/base/karma-shim.js:47940:42)
    at ZoneDelegate.invokeTask (http://localhost:9876/base/karma-shim.js:48564:35)
    at Zone.runTask (http://localhost:9876/base/karma-shim.js:48453:47)
    at drainMicroTaskQueue (http://localhost:9876/base/karma-shim.js:48700:35)
Run Code Online (Sandbox Code Playgroud)

! - 组件

import { Component, OnInit } from '@angular/core';
import { TestService } from '../components/service/TestService';
@Component({
  selector: 'my-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss'],
  providers: [TestService]
})
export class HomeComponent implements OnInit {

  constructor(private testService: TestService) {
    // Do stuff
  }

  ngOnInit() {
    console.log('Hello Home', this.testService.getUsers());
  }

}
Run Code Online (Sandbox Code Playgroud)

! - 服务

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

@Injectable()
export class TestService {
  constructor(public http: Http) {}

  getUsers() {
    return this.http.get('http://foo.bar');
  }
}
Run Code Online (Sandbox Code Playgroud)

! - 考试

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

import {BaseRequestOptions, Response, ResponseOptions, Http} from '@angular/http';
import { MockBackend, MockConnection } from '@angular/http/testing';

import { BrowserDynamicTestingModule, platformBrowserDynamicTesting } from '@angular/platform-browser-dynamic/testing';
import {TestService} from './TestService';

TestBed.initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting());

describe('Http', () => {

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

  beforeEach(inject([MockBackend], (backend: MockBackend) => {
    const baseResponse = new Response(new ResponseOptions({ body: 'got response' }));
    backend.connections.subscribe((c: MockConnection) => c.mockRespond(baseResponse));
  }));

  it('should return response when subscribed to getUsers', inject([TestService], (testService: TestService) => {
    testService.getUsers().subscribe((res: Response) => {
      expect(res.text()).toBe('got response');
    });
  }));

});
Run Code Online (Sandbox Code Playgroud)

小智 11

我已经修复了这个问题,做了以下事情:

移动TestBed.initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting());到该beforeAll功能,所以它看起来像这样

describe('Http', () => {
    beforeAll( ()=> {
        TestBed.initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting());
    });
    beforeEach( () => {
       TestBed.configureTestingModule({
           providers : [...]
       }
    });
    it('your tests...', inject([Provider], (provider:Provider)=>{});
Run Code Online (Sandbox Code Playgroud)

  • 这应该是公认的答案。非常感谢。它就像一个魅力。 (2认同)

Fla*_*ken 11

您可能还会收到此消息Cannot set base providers because it has already been called(\xe2\x80\xa6)

\n

因为你的jest 配置文件中有一个setupFilesAfterEnv

\n

其中之一setupFiles运行代码,在您之前设置基本提供程序。

\n

例子:

\n

笑话配置.js

\n
{\n  setupFilesAfterEnv: [\'<rootDir>/setup-jest.ts\'],\n}\n
Run Code Online (Sandbox Code Playgroud)\n

安装程序-jest.ts

\n
# remove this line\n`import \'jest-preset-angular/setup-jest\';`\n
Run Code Online (Sandbox Code Playgroud)\n