2016-01-12 3 views
2

Я пытаюсь использовать fakeAsync для тестирования компонента Angular 2, но переменная прибора не устанавливается. Фактически, вызов вызова обещания не вызывается. Вот код:Угловое тестирование с помощью fakeAsync

@Component({ 
    template: '', 
    directives: [GroupBox, GroupBoxHeader] 
}) 
class TestComponent { 
    expandedCallback() { this.expandedCalled = true; } 
} 

it('testing...', inject([TestComponentBuilder], fakeAsync((tcb) => { 

    var fixture; 

    tcb.createAsync(TestComponent).then((rootFixture) => { 
    fixture = rootFixture 
    }); 

    tick(); 

    fixture.detectChanges(); 
}))); 

Когда я запускаю этот код, я получаю:

Failed: Cannot read property 'detectChanges' of undefined TypeError: Cannot read property 'detectChanges' of undefined

Я не могу понять, почему обратный вызов не увольняет. В этом хранилище он отлично работает: https://github.com/juliemr/ng2-test-seed/blob/master/src/test/greeting-component_test.ts

Любые подсказки?

Примечание: Я использую ES6, Traceur, Angular 2 beta, Karma и Jasmine.

------ ОБНОВЛЕНИЕ ------

следует, репозиторий с неисправным тестом:

https://github.com/cangosta/ng2_testing_fakeasync

+0

Похоже проблема с TestComponent. Если я удалю строку «директивы: [GroupBox]» из определения компонента, ошибка больше не возникает – cangosta

+0

Кажется, что это ошибка в угловой структуре 2: https://github.com/angular/angular/issues/5601 – cangosta

+0

Да https://github.com/juliemr/ng2-test-seed/blob/master/src/test/greeting-component_test.ts работает, потому что шаблон встроен –

ответ

2

TestComonentBuilder не работает с templateUrlhttps://github.com/angular/angular/issues/5662

+1

Спасибо за ваш ответ Gunter. Даже если я переведу код в закрытие, он никогда не вызывается ... Я попытаюсь создать репо, где я могу реплицировать ошибку. – cangosta

2

Пробег: https://github.com/antonybudianto/angular2-starter/blob/master/app/simplebind/child.component.spec.ts#L15

Th Вы должны создать тестовый фиктивный компонент (например, TestComponent) и зарегистрировать компонент, который хотите протестировать, в directives: [...] и использовать template: <my-cmp></my-cmp>, затем передать TestComponent в tsb.createAsync(TestComponent)... и использовать injectAsync.

Я предпочитаю этот способ, так как я могу легко издеваться над данными из родительского элемента и передавать любые данные ввода и вывода в/из компонента.

import { 
 
it, 
 
injectAsync, 
 
describe, 
 
expect, 
 
TestComponentBuilder, 
 
ComponentFixture 
 
} from 'angular2/testing'; 
 
import { Component } from 'angular2/core'; 
 
import { ChildComponent } from './child.component'; 
 

 
@Component({ 
 
    selector: 'test', 
 
    template: ` 
 
    <child text="Hello test" [(fromParent)]="testName"></child> 
 
    `, 
 
    directives: [ChildComponent] 
 
}) 
 
class TestComponent { 
 
    testName: string; 
 

 
    constructor() { 
 
     this.testName = 'From parent'; 
 
    } 
 
} 
 

 
let testFixture: ComponentFixture; 
 
let childCompiled; 
 
let childCmp: ChildComponent; 
 

 
describe('ChildComponent',() => { 
 
    it('should print inputs correctly', injectAsync([TestComponentBuilder], 
 
    (tsb: TestComponentBuilder) => { 
 
     return tsb.createAsync(TestComponent).then((fixture) => { 
 
      testFixture = fixture; 
 
      testFixture.detectChanges(); 
 

 
      childCompiled = testFixture.nativeElement; 
 
      childCmp = testFixture.debugElement.children[0].componentInstance; 
 

 
      expect(childCompiled).toBeDefined(); 
 
      expect(childCmp).toBeDefined(); 
 
      expect(childCompiled.querySelector('h6')) 
 
       .toHaveText('From parent'); 
 
      expect(childCompiled.querySelector('h5')) 
 
       .toHaveText('Hello test'); 
 
     }); 
 
    })); 
 

 
    it('should trigger changeMe event correctly',() => { 
 
     childCmp.changeMe(); 
 
     testFixture.detectChanges(); 
 
     expect(childCmp.num).toEqual(1); 
 
     expect(childCompiled.querySelector('h6')) 
 
      .toHaveText('Changed from child. Count: ' + childCmp.num); 
 
    }); 
 
});

+0

Не могли бы вы добавить код внутри своего ответа вместо ссылки на github? –

Смежные вопросы