使用 Angular 2 的 TestComponentBuilder 让我很困惑

Using Angular 2's TestComponentBuilder confuses me

我正在开发一个 Angular 2-rc3 应用程序,我设置了一些单元测试,它们正在运行,耶!我只是不明白为什么必须按照他们的方式编写它们。更神奇的是,all the I see 有相同的方法。具体来说,这些问题在我的列表中排在首位:

  1. 为什么每个unittest都配置了TestComponentBuilder

    it('shows list of blog items by default', inject([TestComponentBuilder], (tcb: TestComponentBuilder) => {
        return tcb
        .overrideProviders(BlogRoll, [provide(BlogService, {
                useValue: mockBlogService
            })])
            .createAsync(BlogRoll)
            .then((fixture) => {
            // actual test code
        });
    });
    

    每个单元测试已经多了七行代码,我的代码的可读性因此受到很大影响。我试过将它放在 beforeEach():

    beforeEach(inject([TestComponentBuilder], (tcb: TestComponentBuilder) => {
        console.log('beforeEach');
        return tcb.overrideProviders(BlogRoll, [provide(BlogService, {
                useValue: mockBlogService
            })])
            .createAsync(BlogRoll)
            .then(fixture => {
                // this never gets printed
                console.log('in then:', fixture.componentInstance);
            });
    }));
    

    但是 Karma 似乎无法处理异步,then 中的所有内容都不会被执行。这是一个错误还是有意为之,我们不应该这样做吗?

  2. 为什么这个组件的创建需要异步进行? TestComponentBuilder class 上有一个 createSync(),我们不能用那个吗?当然我试过了,发现函数签名不同:createAsync(rootComponentType: Type) : Promise<ComponentFixture<any>>createSync(componentFactory: ComponentFactory<C>) : ComponentFixture<C>。为什么我们这里需要一个组件工厂,为什么我们在创建组件异步时不需要它? // 更新:RC4 已发布,createSync() 现在接受类型。太棒了

我的理智已经谢谢你了!

  1. angular2-material 测试组织得很好,并且在 beforEach 中设置了 TestComponentBuilder,尽管它们仍然会为每个测试调用 createAsync。然后,您可以像这样嵌套 createAsync 调用:

    describe('Example', () => {
            let fixture;
            let builder: TestComponentBuilder;
    
            beforeEach(injectAsync([TestComponentBuilder], (tcb: TestComponentBuilder) => {
                    builder = tcb;
    
                    builder.createAsync(ExampleComponent).then(        
                         fixture = f;
                    });
            });
    
    
            it('Test 1', () => {
                         expect(fixture.componentInstance).not.toEqual(null);
            });
    });
    

Angular 2 final 已经发货,TestComponentBuilder class 已被 TestBed 取代,这让我感到困惑。