service(具有依赖性)使用angular2进行单元测试

时间:2016-07-19 14:22:14

标签: angular

我从angular2单元测试开始并遇到问题。 我的服务接受 ApplicationRef ComponentResolver 作为参数 然后,该服务使用 ComponentResolver 动态加载组件。 我的问题是如何将单元测试传递给该服务上述参数?

1 个答案:

答案 0 :(得分:0)

此示例是否可以帮助您:

import {Component, provide} from '@angular/core';
import {ComponentFactory} from '@angular/core/src/linker/component_factory';
import {ComponentResolver, ReflectorComponentResolver} from '@angular/core/src/linker/component_resolver';
import {ReflectionInfo, reflector} from '@angular/core/src/reflection/reflection';
import {afterEach, beforeEach, beforeEachProviders, ddescribe, describe, expect, iit, inject, it, xdescribe, xit} from '@angular/core/testing/testing_internal';
import {AsyncTestCompleter} from '@angular/core/testing/testing_internal';
import {Console} from '../../src/console';

class DummyConsole implements Console {
  log(message: string) {}
  warn(message: string) {}
}

export function main() {
  describe('Compiler', () => {
    var someCompFactory: any /** TODO #9100 */;
    var compiler: ComponentResolver;

    beforeEach(() => {
      someCompFactory = new ComponentFactory(null, null, null);
      reflector.registerType(SomeComponent, new ReflectionInfo([someCompFactory]));
      compiler = new ReflectorComponentResolver(new DummyConsole());
    });

    it('should read the template from an annotation',
       inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
         compiler.resolveComponent(SomeComponent).then((compFactory: ComponentFactory<any>) => {
           expect(compFactory).toBe(someCompFactory);
           async.done();
           return null;
         });
       }));

    it('should throw when given a string',
       inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
         compiler.resolveComponent('someString').catch((e) => {
           expect(e.message).toContain('Cannot resolve component using \'someString\'.')
               async.done();
         });
       }));
  });
}

class SomeComponent {}