Angular 4 Unit Tests (TestBed) extremely slow
describe('Test name', () => {
configureTestSuite();
beforeAll(done => (async () => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule, NgReduxTestingModule],
providers: []
});
await TestBed.compileComponents();
})().then(done).catch(done.fail));
it(‘your test', (done: DoneFn) => {
});
});
Create new file:
import { getTestBed, TestBed, ComponentFixture } from '@angular/core/testing';
import { } from 'jasmine';
export const configureTestSuite = () => {
const testBedApi: any = getTestBed();
const originReset = TestBed.resetTestingModule;
beforeAll(() => {
TestBed.resetTestingModule();
TestBed.resetTestingModule = () => TestBed;
});
afterEach(() => {
testBedApi._activeFixtures.forEach((fixture: ComponentFixture<any>) => fixture.destroy());
testBedApi._instantiated = false;
});
afterAll(() => {
TestBed.resetTestingModule = originReset;
TestBed.resetTestingModule();
});
};
It turned out the problem is with Angular, as addressed on Github
Below a workaround from the Github discussion that dropped the time for running the tests from more than 40 seconds to just 1 second (!) in our project.
const oldResetTestingModule = TestBed.resetTestingModule;
beforeAll((done) => (async () => {
TestBed.resetTestingModule();
TestBed.configureTestingModule({
// ...
});
function HttpLoaderFactory(http: Http) {
return new TranslateHttpLoader(http, "/api/translations/", "");
}
await TestBed.compileComponents();
// prevent Angular from resetting testing module
TestBed.resetTestingModule = () => TestBed;
})()
.then(done)
.catch(done.fail));