Unit test error: Cannot call Promise.then from within a sync test
I got the same error for a different reason. I put a TestBed.get(Dependency)
call within a describe
block. The fix was moving it to the it
block.
Wrong:
describe('someFunction', () => {
const dependency = TestBed.get(Dependency); // this was causing the error
it('should not fail', () => {
someFunction(dependency);
});
});
Fixed:
describe('someFunction', () => {
it('should not fail', () => {
const dependency = TestBed.get(Dependency); // putting it here fixed the issue
someFunction(dependency);
});
});
Move your variable initialization inside a beforeEach.
You shouldn't be getting things out of the TestBed or managing the fixture or component in the describe
scope. You should only do these things within the scope of a test run: inside a beforeEach
/beforeAll
, afterEach
/afterAll
, or inside an it
.
describe(("test input "), () => {
let comp: ToDoComponent;
let fixture: ComponentFixture<ToDoComponent>;
let de: DebugElement;
let el: HTMLElement;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ToDoComponent],
imports: [FormsModule]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(ToDoComponent);
comp = fixture.componentInstance;
de = fixture.debugElement.query(By.css("h1"));
el = de.nativeElement;
})
it('should display a different test title', () => {
comp.pageTitle = 'Test Title';
fixture.detectChanges();
expect(el.textContent).toBe('Test Title423');
});
});
See also
- https://angular.io/docs/ts/latest/guide/testing.html#!#waiting-compile-components