2016-12-07 84 views
1

我目前正在为我的Angular2组件使用templateUrl属性编写一个模块的测试模块,因此需要在测试之前编译TestBed.compileComponents异步调用。Angular2测试。 Promise从未解决TestBed.compileComponents

我遇到的问题是,承诺回调(然后)函数中的任何内容都不会运行...就好像承诺没有解决。

这是我的代码。

模块:

import { Component } from "@angular/core"; 

@Component({ 
    selector: 'categories-component', 
    templateUrl: '/app/views/catalog/categories/categories-dashboard.html', 
    moduleId: module.id 
}) 

export class CategoriesComponent { 
    title: 'Categories; 
} 

HTML模板:

<h1>{{ title }}</h1> 

且测试模块:

import {TestBed, ComponentFixture, ComponentFixtureAutoDetect, async} from "@angular/core/testing"; 
import { By} from "@angular/platform-browser"; 
import { CategoriesComponent } from "../../../../components/catalog/categories/CategoriesComponent"; 
import { DebugElement } from "@angular/core"; 

let comp: CategoriesComponent; 
let fixture: ComponentFixture<CategoriesComponent>; 
let de:  DebugElement; 
let el:  HTMLElement; 

describe('CategoriesComponent',() => { 
    beforeEach(() => { 
     TestBed.configureTestingModule({ 
      declarations: [ CategoriesComponent ], 
      providers: [ 
       { provide: ComponentFixtureAutoDetect, useValue: true } 
      ] 
     }); 
    }); 

    it('should display original title',() => { 
     TestBed.compileComponents() 
      .then(() => { 
       fixture = TestBed.createComponent(CategoriesComponent); 

       comp = fixture.componentInstance; // BannerComponent test instance 

       // query for the title <h1> by CSS element selector 
       de = fixture.debugElement.query(By.css('h1')); 
       el = de.nativeElement; 

       expect(el.textContent).toContain(comp.title); 
      }); 

}); 

});

如您所见,在我的测试中,我调用compileComponents异步编译测试模块,然后在回调中创建测试组件的fixture和实例。这一切都没有得到运行,我添加了这个永远不会触发的断点。

任何人都可以指出我在做什么错在这里?

谢谢!

回答

2

这是因为测试是同步

it('...',() => { 
}) 

回调这里执行和测试完成后的回调函数执行之后。

但问题是,你有你的代码在异步回调

it('...',() => { 
    TestBed.compileComponents().then(() => { 
    // asynchronous 
    // code not executed 
    }) 
}) 

所以在测试完成之前异步代码永远不会被执行。

这可以通过几种方法处理。您可以使用本机茉莉done回调

it('...', (done) => { 
    TestBed.compileComponents().then(() => { 
    /// do stuff 

    done(); 
    }) 
}) 

在这里,茉莉花通过你的回调函数。当你完成所有的异步工作时,你可以调用它。

另一种方式,就是使用Angular async

import { async } from '@anguar/core/testing'; 

it('...', async(() => { 
    TestBed.compileComponents().then(() => { 

    }) 
})) 

这样做是在测试区,其跟踪的所有异步任务包的测试,并完成测试毕竟异步任务有完全的。在茉莉花环境中,在异步任务完成之后,测试区域实际上将调用茉莉花done回调。

+0

嗨,谢谢你的回答。我确实认为是这种情况,但是当我使用这些解决方案时,出现以下错误。错误:超时 - 异步回调未在由jasmine.DEFAULT_TIMEOUT_INTERVAL指定的超时内调用。 – devoncrazylegs

+0

我不知道。我几次看到这个错误。我不记得问题是什么。你是否使用了错误(与Angular 2和业力有关)? –

+0

尝试并将模板移至'@ Component.template'并摆脱'templateUrl'并且不要调用'compileComponents'。看看它是否有效。如果它有效,那么这是'compileComponents'的问题。不知道什么会导致它。至少如果你把问题缩小到这个范围,它会缩小搜索范围。 –