3

Я создал новый проект с NG-CLI (beta.15) и модифицировал app.component.spec изменить beforeEach к к beforeAll, и это вызвало тесты на провал с следующая погрешность:Угловой тест 2 CLI жасмин блок не при использовании beforeAll вместо beforeEach

Failed: Cannot create the component AppComponent as it was not imported into the testing module!

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

Вот модифицированная спецификация:

import { TestBed, async } from '@angular/core/testing'; 
import { AppComponent } from './app.component'; 

describe('App: Ng2CliTest2',() => { 
    beforeAll(() => { 
    TestBed.configureTestingModule({ 
     declarations: [ 
     AppComponent 
     ], 
    }); 
    }); 

    it('should create the app', async(() => { 
    let fixture = TestBed.createComponent(AppComponent); 
    let app = fixture.debugElement.componentInstance; 
    expect(app).toBeTruthy(); 
    })); 

    it(`should have as title 'app works!'`, async(() => { 
    let fixture = TestBed.createComponent(AppComponent); 
    let app = fixture.debugElement.componentInstance; 
    expect(app.title).toEqual('app works!'); 
    })); 

    it('should render title in a h1 tag', async(() => { 
    let fixture = TestBed.createComponent(AppComponent); 
    fixture.detectChanges(); 
    let compiled = fixture.debugElement.nativeElement; 
    expect(compiled.querySelector('h1').textContent).toContain('app works!'); 
    })); 
}); 

Затем я изменил спецификации этого и первые два испытания проходят и третий выдает следующее сообщение:

Failed: Attempt to use a destroyed view: detectChanges

import { TestBed, async } from '@angular/core/testing'; 
import { AppComponent } from './app.component'; 

let fixture; 
let app; 

describe('App: Ng2CliTest2',() => { 
    beforeAll(() => { 
    TestBed.configureTestingModule({ 
     declarations: [ 
     AppComponent 
     ], 
    }); 
    fixture = TestBed.createComponent(AppComponent); 
    app = fixture.debugElement.componentInstance;   
    }); 

    it('should create the app', async(() => { 
    expect(app).toBeTruthy(); 
    })); 

    it(`should have as title 'app works!'`, async(() => { 
    expect(app.title).toEqual('app works!'); 
    })); 

    it('should render title in a h1 tag', async(() => { 
    fixture.detectChanges(); 
    let compiled = fixture.debugElement.nativeElement; 
    expect(compiled.querySelector('h1').textContent).toContain('app works!'); 
    })); 
}); 

Я не Не понимаю, почему есть какие-то неудачи.

ответ

5

не зная, Угловое фактически resets the testing module в ней свою собственную тайные beforeEach (see testing.ts)

var _global = <any>(typeof window === 'undefined' ? global : window); 

// Reset the test providers and the fake async zone before each test. 
if (_global.beforeEach) { 
    _global.beforeEach(() => { 
    TestBed.resetTestingModule(); 
    resetFakeAsyncZone(); 
    }); 
} 

Я даже не пробовал это, но вы хотите знать, как это работает, может быть, попробовать и (безопасно) отключить эту функцию, это то, что я выяснил:

Где-то в вашей конфигурации вы импортировали

@angular/core/bundles/core-testing.umd.js 

Это много раз в файле karma-test-shim.js. Этот файл содержит почти все утилиты тестирования, которые мы используем в тесте Angular. Это в значительной степени компиляция всего, что экспортируется из testing module. Сюда входит вышеупомянутый файл тестирования, который добавляет глобальный вызов beforeEach.

И только если это не очевидно из приведенной выше информации, ваш beforeAll подходит только для первого теста, затем Угловая сбрасывает тестовую кровать. Итак, в следующем тесте вы пытаетесь создать компонент из пустой тестовой кровати.

+0

Удивительная находка, чувак, thx. – HisDivineShadow

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