测试-无法解析(ClassName)的所有参数 [英] Testing - Can't resolve all parameters for (ClassName)

查看:83
本文介绍了测试-无法解析(ClassName)的所有参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个ApiService类,以便能够使用我们自己的序列化器和其他功能来处理我们的自定义API查询.

I created an ApiService class to be able to handle our custom API queries, while using our own serializer + other features.

ApiService的构造函数签名为:

constructor(metaManager: MetaManager, connector: ApiConnectorService, eventDispatcher: EventDispatcher);

  • MetaManager是可处理的服务,用于处理api的元数据.
  • ApiConnectorService是包装Http来添加我们的自定义标头和签名系统的服务.
  • EventDispatcher基本上是打字稿中Symfony的事件分配器系统.
    • MetaManager is an injectable service that handles api's metadatas.
    • ApiConnectorService is a service which is wrapping Http to add our custom headers and signature system.
    • EventDispatcher is basically Symfony's event dispatcher system, in typescript.
    • 当我测试ApiService时,我在beforeEach中进行了初始化:

      When I test the ApiService, I do an initialization in beforeEach:

      beforeEach(async(() => {
          TestBed.configureTestingModule({
              imports  : [
                  HttpModule
              ],
              providers: [
                  ApiConnectorService,
                  ApiService,
                  MetaManager,
                  EventDispatcher,
                  OFF_LOGGER_PROVIDERS
              ]
          });
      }));
      

      它工作正常.

      然后我添加第二个规格文件,该文件用于ApiConnectorService,并带有以下beforeEach:

      Then I add my second spec file, which is for ApiConnectorService, with this beforeEach:

      beforeEach(async(() => {
          TestBed.configureTestingModule({
              imports  : [HttpModule],
              providers: [
                  ApiConnectorService,
                  OFF_LOGGER_PROVIDERS,
                  AuthenticationManager,
                  EventDispatcher
              ]
          });
      }));
      

      所有测试均失败,并显示以下错误:

      And all the tests fail with this error:

      错误:无法解析ApiService的所有参数:(MetaManager,?,EventDispatcher).

      Error: Can't resolve all parameters for ApiService: (MetaManager, ?, EventDispatcher).

      • 如果我从加载的测试中删除api-connector-service.spec.ts(ApiConnectorService的规格文件),则ApiService的测试将成功.
      • 如果我从加载的测试中删除api-service.spec.ts(ApiService的规格文件),则ApiConnectorService的测试将成功.
        • If I remove api-connector-service.spec.ts (ApiConnectorService's spec file) from my loaded tests, ApiService's tests will succeed.
        • If I remove api-service.spec.ts (ApiService's spec file) from my loaded tests, ApiConnectorService's tests will succeed.
        • 为什么会出现此错误?看来我两个文件之间的上下文存在冲突,我不知道为什么以及如何解决此问题.

          Why do I have this error? It seems like the context between my two files are in conflict and I don't know why and how to fix this.

          推荐答案

          这是因为在测试环境中无法从HttpModule解析Http服务.它取决于平台浏览器.在测试期间,您甚至都不应该尝试进行XHR调用.

          It's because the Http service can't be resolved from the HttpModule, in a test environment. It is dependent on the platform browser. You shouldn't even be trying to to make XHR calls anyway during the tests.

          因此,Angular为Http服务提供了MockBackend可供使用.我们使用此模拟后端在测试中订阅连接,并且可以在建立每个连接时模拟响应.

          For this reason, Angular provides a MockBackend for the Http service to use. We use this mock backend to subscribe to connections in our tests, and we can mock the response when each connection is made.

          这是一个简短的完整示例,您可以根据其进行操作

          Here is a short complete example you can work off of

          import { Injectable } from '@angular/core';
          import { async, inject, TestBed } from '@angular/core/testing';
          import { MockBackend, MockConnection } from '@angular/http/testing';
          import {
            Http, HttpModule, XHRBackend, ResponseOptions,
            Response, BaseRequestOptions
          } from '@angular/http';
          
          @Injectable()
          class SomeService {
            constructor(private _http: Http) {}
          
            getSomething(url) {
          	return this._http.get(url).map(res => res.text());
            }
          }
          
          describe('service: SomeService', () => {
            beforeEach(() => {
          	TestBed.configureTestingModule({
          	  providers: [
          		{
          		  provide: Http, useFactory: (backend, options) => {
          			return new Http(backend, options);
          		  },
          		  deps: [MockBackend, BaseRequestOptions]
          		},
          		MockBackend,
          		BaseRequestOptions,
          		SomeService
          	  ]
          	});
            });
          
            it('should get value',
          	async(inject([SomeService, MockBackend],
          				 (service: SomeService, backend: MockBackend) => {
          
          	backend.connections.subscribe((conn: MockConnection) => {
          	  const options: ResponseOptions = new ResponseOptions({body: 'hello'});
          	  conn.mockRespond(new Response(options));
          	});
          
          	service.getSomething('http://dummy.com').subscribe(res => {
          	  console.log('subcription called');
          	  expect(res).toEqual('hello');
          	});
            })));
          });

          这篇关于测试-无法解析(ClassName)的所有参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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